Splitting a float into bytes:
John Machin
sjmachin at lexicon.net
Wed Jul 26 19:50:41 EDT 2006
Michael Yanowitz wrote:
> Hello:
>
> For some reason I can't figure out how to split
> a 4-byte (for instance) float number (such as 3.14159265359)
> into its 4-bytes so I can send it via a socket to another
> computer.
> For integers, it is easy, I can get the 4 bytes by anding like:
> byte1 = int_val & 0x000000FF
> byte2 = int_val & 0x0000FF00
> byte3 = int_val & 0x00FF0000
> byte4 = int_val & 0xFF000000
Errrmmm ... I think you need the right shift operator e.g.
byte4 = (int_val & 0xFF000000) >> 24
but assert 0 <= byte4 <= 255 may fail under some circumstances
so (better):
byte4 = (int_val >> 24) & 0xFF
# absolutely guaranteed to pass that assertion
BUT why muck around with all that when you can use struct.pack???
More information about the Python-list
mailing list