Python - bit manipulation and decoding signed value in 2's complement

Status
Not open for further replies.

stodge

Ars Tribunus Militum
1,907
I seem to be having a brain fart today as my mind is just blank. I'm parsing datagrams to extract some data. I have an x,y coordinate pair in 8 bytes. My ICD tells me:

bytes 1-4 are the X position
bytes 5-8 are the Y position

The 64th bit of the X position is the sign bit, so it's in 2's complement. The 32nd bit is the sign bit for the Y position.

So to decode the X coordinate, do I reverse the top four bytes:

ABCD ==> DCBA

And then the sign bit is the 8th bit of the first byte (A)?

*whacks head against wall*
 
I'd expect that all you have to do is read the bytes into your 32-bit int, account for endianness, and the sign bit will be exactly where it ought to be.

The way you're describing this is a bit odd because bit order and byte order aren't related, so it doesn't make much sense to talk about 'the 64th bit' when you have a stream of bytes. It's probably better to talk (and think) in terms of significance instead.
 

Jonathon

Ars Legatus Legionis
17,645
Subscriptor
Izmunuti":2qoc3k99 said:
x, y = unpack('<l<l', data);
This. You shouldn't have to go around twiddling with bits in python unless whomever designed your protocol is insane (stuff like bitfields where part of the bitfield actually represents an integer or whatever). Unpack will do it for you and give you a nice, pretty python integer, and pack will do the reverse (if you have to send datagrams back).

They're both in the struct package.

(I have a nice little rule about Python... if I want to do it, it's almost always in the standard library. :))
 
Status
Not open for further replies.