Pythonic bit twiddling
Darrell
dgallion1 at yahoo.com
Thu Feb 21 23:20:40 EST 2002
Working with unsigned is a pain.
>>> a=0x80000000
>>> hex(a>>32)
'0xffffffff'
>>> int('0x80000000',16)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: int() literal too large: 0x80000000
>>> eval('0x80000000')
-2147483648
>>>
And eval doesn't need to be told the number base in advance.
Other than the 0x... that is.
Longs help.
>>> b=0x80000000L
>>> b
2147483648L
>>> hex(b)
'0x80000000L'
>>> hex(b>>32)
'0x0L'
>>> hex(b>>31)
'0x1L'
>>>
But there are problems with this also.
>>> struct.pack("i",b)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
OverflowError: long int too large to convert to int
>>> struct.pack("l",b)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
OverflowError: long int too large to convert to int
>>> struct.pack("l",int(b))
Traceback (most recent call last):
File "<stdin>", line 1, in ?
OverflowError: long int too large to convert to int
You can play games to get around this.
>>> bs=b>>1
>>> bs=bs<<1
>>> struct.pack("i",bs)
'\x00\x00\x00\x80'
>>>
--Darrell
Paul Rubin wrote:
>
> Am I missing something? Python has the usual bit operations that work
> on ints.
>
> a = do_some_stuff(byte >> 4) # upper nibble
> b = do_similar_stuff(byte & 0x0f) # lower nibble
> new_byte = (a << 4) + b # assume a and b are nibble results
More information about the Python-list
mailing list