Binary number manipulation

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Matthew A. Berglund

    Binary number manipulation

    Hello All!

    I am very new to python so I am working on some ass-umptions which may be incorrect (please forgive me).

    I am working on a problem that requires me to take 2 decimal integers, each of which represents half of a word. I need to slap these things together and get out another decimal integer.
    A couple of questions:
    1. Is there a way to typecast a variable as a binary?
    2. If 1 is no, does that mean that I need to do all the manipulation in some icky string format and then go back?

    I do see the bit-wise operations available and this looks like I need to simply perform these on my integers? Can it really be that simple?

    Thanks,
    Matt
  • Irmen de Jong

    #2
    Re: Binary number manipulation

    Matthew A. Berglund wrote:
    [color=blue]
    > I am working on a problem that requires me to take 2 decimal integers, each
    > of which represents half of a word. I need to slap these things together
    > and get out another decimal integer.[/color]
    [...][color=blue]
    > I do see the bit-wise operations available and this looks like I need to
    > simply perform these on my integers? Can it really be that simple?[/color]

    Probably. Consider the following (typed at the interactive prompt):
    [color=blue][color=green][color=darkred]
    >>> a=0x1234
    >>> b=0xabcd
    >>> i=a<<16 | b
    >>> print i[/color][/color][/color]
    305441741[color=blue][color=green][color=darkred]
    >>> print hex(i)[/color][/color][/color]
    0x1234abcd

    This example assumes that both words are 16 bits.
    There are some signed/unsinged issues, be warned.


    --Irmen

    Comment

    Working...