Convert hex to float

后端 未结 5 1296
清歌不尽
清歌不尽 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:53

    I'm guessing this question relates to this one and you are working with 4 bytes rather than 8 hex digits.

    "\x41\x91\x33\x33" is a 4 byte string even though it looks like 16

    >>> len("\x41\x91\x33\x33")
    4
    >>> import struct  
    >>> struct.unpack(">fff","\x41\x97\x33\x33\x41\x99\x5C\x29\x47\x0F\xC6\x14")
    (18.899999618530273, 19.170000076293945, 36806.078125)
    

    If you do need to deal with the string of hexdigits rather than the actual bytes, you can use struct.pack to convert it, like this

    >>> for hx in ["41973333","41995C29","470FC614"]:
    ...     print(struct.unpack(">f",struct.pack(">i",int(hx,16)))[0])
    ... 
    18.8999996185
    19.1700000763
    36806.078125
    

提交回复
热议问题