Skip to content

Instantly share code, notes, and snippets.

@ydm
Last active October 21, 2015 13:40
Show Gist options
  • Select an option

  • Save ydm/8bf865b147f5d6168074 to your computer and use it in GitHub Desktop.

Select an option

Save ydm/8bf865b147f5d6168074 to your computer and use it in GitHub Desktop.
Prints the value of a binary representation of a binary32 float number
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# namespace
# {
# void printBinary(const float value)
# {
# char s[33];
# union {
# float f;
# unsigned char c[sizeof(float)];
# } u;
# u.f = value;
# for (size_t i = sizeof(float); i-- != 0;) {
# for (unsigned j = 8; j-- != 0;) {
# s[31 - (i * 8 + j)] = (u.c[i] & (1u << j)) ? '1' : '0';
# }
# }
# s[32] = '\0';
# printf("%s", s);
# }
# } // namespace
radix = 2
coefficients = [1 / (radix**i) for i in range(0, 24)]
def sign(s):
i = int(s, radix)
if i == 0: # (-1) ^ 0 = 1
return 1
elif i == 1: # (-1) ^ 1 = -1
return -1
raise ValueError
def exp(s):
i = int(s, radix)
if 0 <= i <= 255:
return i - 127
raise ValueError
def coef(s):
return sum(
coefficients[i] for (i, bit) in enumerate(s, start=1)
if bit == '1'
)
def b2f(b):
b = b.replace(' ', '').strip()
s = sign(b[0])
e = exp(b[1:9])
c = coef(b[9:32])
# print('s={}, e={}, c={}'.format(s, e, c))
return s * (1 + c) * (radix**e)
def main():
f = '0 01111100 01000000000000000000000'
# f = '10000100 00011010 00110111 01100000'
print(b2f(f))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment