2

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

smci
  • 32,567
  • 20
  • 113
  • 146
  • What Python version and operating system? I'm running Python 2.5.1 on Linux and both statements work as expected for me. – David Z Jan 23 '09 at 22:57

4 Answers4

4
>>> 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.

Community
  • 1
  • 1
Federico A. Ramponi
  • 46,145
  • 29
  • 109
  • 133
2

You need to use long integers.

foo = 0xDEADBEEFCAFEBABEL
fooLow = foo & 0xFFFFFFFFL
Serafina Brocious
  • 30,433
  • 12
  • 89
  • 114
2

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

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 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.

Community
  • 1
  • 1
alsuren
  • 168
  • 1
  • 2