浮動小数点数とビット表現の変換

浮動小数点数をビット表現に変換したり、ビット表現を浮動小数点数に変換したりすることが多いので、コンバータを作ってみました。

github.com

bfloat16以外の浮動小数点数なら、pythonでも以下のように変換できます。

 $ python3
Python 3.8.2 (default, Jul 16 2020, 14:00:26) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import struct
>>> hex(struct.unpack('Q', struct.pack('d', 1.0))[0])
'0x3ff0000000000000'
>>> hex(struct.unpack('I', struct.pack('f', 1.0))[0])
'0x3f800000'
>>> hex(struct.unpack('H', struct.pack('e', 1.0))[0])
'0x3c00'
>>> struct.unpack('d', struct.pack('Q', 0x3ff0000000000000))[0]
1.0
>>> struct.unpack('f', struct.pack('I', 0x3f800000))[0]
1.0
>>> struct.unpack('e', struct.pack('H', 0x3c00))[0]
1.0

上から順番に

  • fp64->hex
  • fp32->hex
  • fp16->hex
  • hex->fp64
  • hex->fp32
  • hex->fp16

です。