Use Python to realize the conversion between floating-point numbers and hexadecimal based on the 754 standard

We need to use structthe packsum unpackfunction in the built-in library .

The following implements single-precision and double-precision floating-point number conversion.

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))

Output result

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


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

Guess you like

Origin blog.csdn.net/qq_39507748/article/details/110290097