Binary number manipulation

Irmen de Jong irmen at -NOSPAM-REMOVETHIS-xs4all.nl
Fri Nov 28 16:21:57 EST 2003


Matthew A. Berglund wrote:

> 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.
[...]
> 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?

Probably. Consider the following (typed at the interactive prompt):

 >>> a=0x1234
 >>> b=0xabcd
 >>> i=a<<16 | b
 >>> print i
305441741
 >>> print hex(i)
0x1234abcd

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


--Irmen





More information about the Python-list mailing list