Python: convert 2 ints to 32 float

后端 未结 2 1635
别跟我提以往
别跟我提以往 2021-01-02 23:53

How can I combine 2 ints to a single 32bit IEEE floating point ? (each of the 2 ints represent 16 bit) And in the opposite direction: How can I transform a python float into

相关标签:
2条回答
  • 2021-01-03 00:20

    This code takes the 16 bits integers i1 and i2 and convert them to the floating point number 3.14, and vice versa.

    from struct import *
    # Two integers to a floating point
    i1 = 0xC3F5
    i2 = 0x4840
    f = unpack('f',pack('>HH',i1,i2))[0]
    
    # Floating point to two integers
    i1, i2 = unpack('>HH',pack('f',3.14))
    
    0 讨论(0)
  • 2021-01-03 00:25

    The standard struct module can be used to do this easily. Just be careful of your platform endianess but, other than that, it should be a pretty straight-forward application of pack() and unpack().

    0 讨论(0)
提交回复
热议问题