fork download
  1. ''' The struct module in Python is used to convert native Python data types
  2. such as strings and numbers into a string of bytes and vice versa.
  3. '''
  4.  
  5. import struct
  6.  
  7. def convert(num):
  8. packed = struct.pack('>f', num) # big-endian float
  9. return ' '.join(f'{byte:02x}' for byte in packed)
  10.  
  11. print("Test #1")
  12. print(convert(1.0))
  13. print(convert(1.1))
  14.  
  15. print("Test #2")
  16. print(convert(1.5))
  17. print(convert(1.25))
  18. print(convert(1.125))
  19. print(convert(1.0625))
  20. print(convert(1.03125))
  21.  
  22. print("Test #3")
  23. print(convert(3.14159))
Success #stdin #stdout 0.12s 14008KB
stdin
Standard input is empty
stdout
Test #1
3f 80 00 00
3f 8c cc cd
Test #2
3f c0 00 00
3f a0 00 00
3f 90 00 00
3f 88 00 00
3f 84 00 00
Test #3
40 49 0f d0