Matthew
Matthew

Reputation:

Python 2.2: How to get the lower 32 bits out of a 64 bit number?

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

Upvotes: 3

Views: 3026

Answers (4)

Matthew
Matthew

Reputation:

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

Upvotes: 2

alsuren
alsuren

Reputation: 178

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.

Upvotes: 0

Federico A. Ramponi
Federico A. Ramponi

Reputation: 47075

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

Upvotes: 5

Serafina Brocious
Serafina Brocious

Reputation: 30609

You need to use long integers.

foo = 0xDEADBEEFCAFEBABEL
fooLow = foo & 0xFFFFFFFFL

Upvotes: 2

Related Questions