Convert hex to float

后端 未结 5 1251
清歌不尽
清歌不尽 2020-11-27 06:07

How to convert the following hex string to float (single precision 32-bit) in Python?

\"41973333\" -> 1.88999996185302734375E1

\"41995C29\" -> 1.91700         


        
5条回答
  •  有刺的猬
    2020-11-27 06:36

    Slice up the hex strings into 2-character chunks (bytes), make each chunk into the right byte with int formatting, struct.unpack when done. I.e.:

    import struct 
    
    testcases = {
    "41973333": 1.88999996185302734375E1,
    "41995C29": 1.91700000762939453125E1,
    "470FC614": 3.6806078125E4,
    }
    
    def hex2float(s):
        bins = ''.join(chr(int(s[x:x+2], 16)) for x in range(0, len(s), 2))
        return struct.unpack('>f', bins)[0]
    
    for s in testcases:
      print hex2float(s), testcases[s]
    

    emitting, as desired:

    18.8999996185 18.8999996185
    19.1700000763 19.1700000763
    36806.078125 36806.078125
    

提交回复
热议问题