美文网首页
conversion between numpy float16

conversion between numpy float16

作者: JiangPQ | 来源:发表于2021-03-11 20:01 被阅读0次

    Convert a numpy float16 data to hex string

    import numpy as np
    
    a = np.float16('1.125')
    a_hex = hex(a.view(np.int16))  
    

    Remember to view any float format as int befort you hex them. This way you could get the same hex value as np.to_file(a).

    Convert a hex string to numpy float16 data

    import numpy as np
    
    a = np.float16('1.125')
    a_hex_str = hex(a.view(np.int16))  
    
    a_hex_byte = bytes.fromhex(a_hex_str)
    a_int16 = struct.unpack('h', h_hex_byte)  # sometimes you need h_hex_byte[::-1] because of big/little endian
    a_np_int16 = np.int16(a_int16)
    a_np_float16 = a_np_int16.view(np.float16)
    
    assert a_np_float16 == a
    

    A graph to help understand this

    np.float16 ←→  np.int16 ← struct.unpack()
                       ↓             ↑  
                      hex() → bytes.fromhex()
    

    相关文章

      网友评论

          本文标题:conversion between numpy float16

          本文链接:https://www.haomeiwen.com/subject/iduoqltx.html