Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert float('nan') to binary in python?

The title says it all. I know pickle can do it, but I don't really want to open a file just to convert a single number. I want to take float('nan') and send it over the network in its binary format.

like image 723
Grant Curell Avatar asked Mar 13 '26 11:03

Grant Curell


1 Answers

>>> import struct
>>> struct.pack('d', float('nan'))
b'\x00\x00\x00\x00\x00\x00\xf8\x7f'

if you want a double-precision (8-byte) binary representation in little-endian format. See https://docs.python.org/2/library/struct.html for all details of how to use big-endian and/or single-precision (4-byte) format instead.

like image 117
Alex Martelli Avatar answered Mar 15 '26 01:03

Alex Martelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!