Splitting a float into bytes:
spartacus
stephen04 at tiscali.co.uk
Wed Jul 26 15:22:10 EDT 2006
Yes i think you can. If you use the struct module.
>> import struct
>> import math
>>y = struct.pack('!f', math.pi)
>>print repr(y)
'@I\x0f\xdb'
"Michael Yanowitz" <m.yanowitz at kearfott.com> wrote in message
news:mailman.8580.1153939983.27775.python-list at python.org...
> 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
> But if I try to do that with floats I get:
>>>> pi & 0xFF
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: unsupported operand type(s) for &: 'float' and 'int'
>
> Is there some easy way to get what the bytes of the float are?
>
> Thanks in advance:
> Michael Yanowitz
>
>
More information about the Python-list
mailing list