fork(1) download
  1. #!/usr/bin/env python
  2. from math import isnan, copysign, isinf, fabs, frexp, floor
  3.  
  4. NEGATIVE_INFINITY = 0b11111000
  5. POSITIVE_INFINITY = 0b01111000
  6.  
  7. def binary8(f):
  8. """1152.0 -> 0b0_1000_001"""
  9. # https://e...content-available-to-author-only...a.org/wiki/Minifloat#Example
  10. if isnan(f):
  11. return 0b11111111 # example nan
  12.  
  13. negative = copysign(1, f) < 0
  14. if isinf(f):
  15. return NEGATIVE_INFINITY if negative else POSITIVE_INFINITY
  16.  
  17. # 1bit 4bits 3bits
  18. # f = (-1)**sign * 2**(e8 - -2) * (1 + f8 / 2**3)
  19. # f = (m * 2) * 2**(e - 1)
  20. m, e = frexp(fabs(f)) # 0.5 <= m < 1
  21. m *= 2
  22. e -= 1
  23. assert not (isnan(m) or isinf(m))
  24.  
  25. e8 = e - 2
  26. if e8 <= 0: # subnormal
  27. f8 = floor(fabs(f))
  28. e8 = 0
  29. elif e8 >= 0b1111: # infinite
  30. return NEGATIVE_INFINITY if negative else POSITIVE_INFINITY
  31. else: # normalized value
  32. assert 0b0001 <= e8 < 0b1111, (f, sign, e8, f8)
  33. f8 = floor((m - 1) * 2**3)
  34. assert 0 <= f8 < 2**3
  35. return (negative << 7) | (e8 << 3) | f8
  36.  
  37. print("{:08b}".format(binary8(float(input()))))
  38.  
Success #stdin #stdout 0.02s 27648KB
stdin
114688.0
stdout
01110110