Hello,
I have a 64 bit number comprised of various bit fields and I'm writing a simple python utility to parse the number. The problem I'm facing is that the lower 32 bits comprise of one field and using some combination of bit shifts or bit masking doesn't give just the 32 bits.
big_num = 0xFFFFFFFFFFFFFFFF
some_field = (big_num & 0x00FFFF0000000000) # works as expected
field_i_need = big_num & 0x00000000FFFFFFFF # doesn't work
What happens is that field_i_need
is equal to big_num
, not the lower 32 bits.
Am I missing something simple here?
Thanks!
Matthew
-
You need to use long integers.
foo = 0xDEADBEEFCAFEBABEL fooLow = foo & 0xFFFFFFFFL
Federico Ramponi : 0xDEADBEEFCAFEBABE is already interpreted as a longnosklo : -1: no, you don't need to use it explicity. -
>>> big_num = 0xFFFFFFFFFFFFFFFF >>> some_field = (big_num & 0x00FFFF0000000000) # works as expected >>> field_i_need = big_num & 0x00000000FFFFFFFF # doesn't work >>> big_num 18446744073709551615L >>> field_i_need 4294967295L
It seems to work, or I am missing the question. I'm using Python 2.6.1, anyway.
For your information, I asked a somehow-related question some time ago.
Federico Ramponi : Just tried also on Python 2.5.1 and 2.4.5. It always seems to work. -
Obviously, if it's a one-off, then using long integers by appending 'L' to your literals is the quick answer, but for more complicated cases, you might find that you can write clearer code if you look at http://stackoverflow.com/questions/142812/does-python-have-a-bitfield-type since this is how you seem to be using your bitmasks.
I think my personal preference would probably be http://docs.python.org/library/ctypes.html#ctypes-bit-fields-in-structures-unions though, since it's in the standard library, and has a pretty clear API.
-
Hello,
Matthew here, I noticed I had left out one piece of information, I'm using python version 2.2.3. I managed to try this out on another machine w/ version 2.5.1 and everything works as expected. Unfortunately I need to use the older version.
Anyway, thank you all for your responses. Appending 'L' seems to do the trick, and this is a one-off so I feel comfortable with this approach.
Thanks,
Matthew
0 comments:
Post a Comment