conversion between numpy float16

2021-03-11  本文已影响0人  JiangPQ

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()
上一篇下一篇

猜你喜欢

热点阅读