Created
July 16, 2023 16:01
-
-
Save cppio/dd13a969f95627d6d4924a16cd5fab19 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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