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('>d', num) # big-endian double
  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 13996KB
stdin
Standard input is empty
stdout
Test #1
3f f0 00 00 00 00 00 00
3f f1 99 99 99 99 99 9a
Test #2
3f f8 00 00 00 00 00 00
3f f4 00 00 00 00 00 00
3f f2 00 00 00 00 00 00
3f f1 00 00 00 00 00 00
3f f0 80 00 00 00 00 00
Test #3
40 09 21 f9 f0 1b 86 6e