Pythonを使用して、754標準に基づく浮動小数点数と16進数の間の変換を実現します

組み込みstructライブラリのpacksumunpack関数を使用する必要があります

以下は、単精度および倍精度浮動小数点数変換を実装しています。

import struct
import numpy as np

def float_to_hex(f):
    return hex(struct.unpack('<I', struct.pack('<f', f))[0])

def hex_to_float(h):
    i = int(h,16)
    return struct.unpack('<f',struct.pack('<I', i))[0]

def double_to_hex(f):
    return hex(struct.unpack('<Q', struct.pack('<d', f))[0])

def hex_to_double(h):
    i = int(h,16)
    return struct.unpack('<d',struct.pack('<Q', i))[0]

if __name__ == '__main__':
    f1 = np.array([17.5,-17.5,77.3,-77.3],np.float32)
    f2 = np.array([17.5, -17.5, 77.3, -77.3], np.float64)
    h1 = []
    h2 = []
    for i in f1:
        print(float_to_hex(i))
        h1.append(float_to_hex(i))
    for i in h1 :
        print(hex_to_float(i))

    for i in f2:
        print(double_to_hex(i))
        h2.append(double_to_hex(i))
    for i in h2 :
        print(hex_to_double(i))

出力結果

0x418c0000
0xc18c0000
0x429a999a
0xc29a999a
17.5
-17.5
77.30000305175781
-77.30000305175781


0x4031800000000000
0xc031800000000000
0x4053533333333333
0xc053533333333333
17.5
-17.5
77.3
-77.3

おすすめ

転載: blog.csdn.net/qq_39507748/article/details/110290097