Skip to content

Instantly share code, notes, and snippets.

@cppio
Created July 16, 2023 16:01
Show Gist options
  • Select an option

  • Save cppio/dd13a969f95627d6d4924a16cd5fab19 to your computer and use it in GitHub Desktop.

Select an option

Save cppio/dd13a969f95627d6d4924a16cd5fab19 to your computer and use it in GitHub Desktop.
import struct
def float32_bin(x):
x, = struct.unpack("=I", struct.pack("=f", x))
sign, exponent, mantissa = x >> 31, x >> 23 & 0xff, x & 0x7fffff
if exponent != 255:
return f"{['', '-'][sign]}0b{int(exponent != 0)}.{mantissa:023b}p{max(exponent, 1) - 127}"
elif mantissa:
return "nan"
else:
return f"{['', '-'][sign]}inf"
def float64_bin(x):
x, = struct.unpack("=Q", struct.pack("=d", x))
sign, exponent, mantissa = x >> 63, x >> 52 & 0x7ff, x & 0xfffffffffffff
if exponent != 2047:
return f"{['', '-'][sign]}0b{int(exponent != 0)}.{mantissa:052b}p{max(exponent, 1) - 1023}"
elif mantissa:
return "nan"
else:
return f"{['', '-'][sign]}inf"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment