Last active
June 9, 2020 05:26
-
-
Save cdleary/de05250deca2db1a1c8452183c0bb405 to your computer and use it in GitHub Desktop.
Some simple Python float/int helpers
This file contains 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
# Apache2 Licensed: https://www.apache.org/licenses/LICENSE-2.0 | |
import struct | |
float2int = lambda f: struct.unpack('i', struct.pack('f', f))[0] | |
float2hex = lambda f: hex(float2int(f)) | |
MASK_23B = (1 << 23) - 1 | |
assert float2hex(1.0) == '0x3f800000' | |
def float2parts(f): | |
x = float2int(f) | |
s = x >> 31 | |
e = x >> 23 & 0xff | |
f = x & MASK_23B | |
return (s, e, f) | |
assert float2parts(1.0) == (0, 127, 0) | |
def parts2float(t): | |
s, e, f = t | |
assert s & 1 == s | |
assert e & 0xff == e | |
assert f & MASK_23B == f | |
x = s << 31 | e << 23 | f | |
return struct.unpack('f', struct.pack('i', x))[0] | |
for f in (1.0, 1.5, 2.0, 3.75, 0.0625): | |
assert parts2float(float2parts(f)) == f, f |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment