R
Roy Smith
I'm working with marshaling data over a binary wire protocol. I'm
using struct.pack() to handle the low-level encoding of ints. One of
the things I need to do is make sure an int can be represented in 4
bytes. Is there a portable way to do that? For now, I'm doing signed
ints, but I'll certainly have to do unsigned 32-bit ints (and 64-bit
ints) at some point. Not to mention shorts and chars.
At first I thought pack() might raise an exception on a value
overflow, that but doesn't seem to be the case:
Should I be thinking more along the lines of bit masking (and worrying
about all the niggling 2-complement issues) in the Python code? Or is
there some cleaner way to do this?
using struct.pack() to handle the low-level encoding of ints. One of
the things I need to do is make sure an int can be represented in 4
bytes. Is there a portable way to do that? For now, I'm doing signed
ints, but I'll certainly have to do unsigned 32-bit ints (and 64-bit
ints) at some point. Not to mention shorts and chars.
At first I thought pack() might raise an exception on a value
overflow, that but doesn't seem to be the case:
['0xde', '0x9f', '0xff', '0xff'][hex(ord(c)) for c in struct.pack('!i', 999999999999999999999L)]
Should I be thinking more along the lines of bit masking (and worrying
about all the niggling 2-complement issues) in the Python code? Or is
there some cleaner way to do this?