[Python-ideas] Exact integral types in struct
Serhiy Storchaka
storchaka at gmail.com
Tue Mar 20 21:27:24 CET 2012
20.03.12 21:54, Andrew Svetlov написав(ла):
> Floating points from IEEE 754 doesn't depends from machine byte order
> and C double is always coded in 8 bytes as I know,
Full code:
def _floatconstants():
_BYTES = binascii.unhexlify(b'7FF80000000000007FF0000000000000')
if sys.byteorder != 'big':
_BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
nan, inf = struct.unpack('dd', _BYTES)
return nan, inf, -inf
NaN, PosInf, NegInf = _floatconstants()
But in xdrlib.py:
return struct.unpack('>d', data)[0]
And in pickle.py:
self.append(unpack('>d', self.read(8))[0])
Test:
>>> import struct
>>> struct.pack('>d', 1)
b'?\xf0\x00\x00\x00\x00\x00\x00'
>>> struct.pack('<d', 1)
b'\x00\x00\x00\x00\x00\x00\xf0?'
More information about the Python-ideas
mailing list