#16进制转float
import math
def hexstr2ieee745(hexStr):
ret = str();
for x in range(0, len(hexStr), 2):
a = hexStr[x:x + 2];
intItem = int(a, 16);
binnaryStr = bin(intItem)[2:len(bin(intItem))];
binnaryStr = "%(binnary)08d" % {'binnary': int(binnaryStr)}
ret = ret + binnaryStr;
s = int(ret[0]);
n = int(ret[1:9], 2);
mStr = ret[9:len(ret) - 1];
m = float();
print(mStr);
for x in range(1, len(mStr) - 1, 1):
if mStr[x - 1] == "1":
# print(x);
m = m + math.pow(0.5, x);
val = math.pow(-1, s) * (math.pow(2, n - 127)) * (1 + m);
print(val)
return ret;
hexstr2ieee745('421FEC7F')
#16进制与float互转
import struct
import ctypes
def float_to_hex(f):
return hex(struct.unpack('<I', struct.pack('<f', f))[0])
def float2hex(s):
fp = ctypes.pointer(ctypes.c_float(s))
cp = ctypes.cast(fp,ctypes.POINTER(ctypes.c_long))
return hex(cp.contents.value)
def hex_to_float(h):
i = int(h,16)
return struct.unpack('<f',struct.pack('<I', i))[0]
def hex2float(h):
i = int(h,16)
cp = ctypes.pointer(ctypes.c_int(i))
fp = ctypes.cast(cp,ctypes.POINTER(ctypes.c_float))
return fp.contents.value
if __name__ == '__main__':
f = [1.5,-1.5,3.5,-3.5]
h = []
for i in f:
print(float_to_hex(i)," | ",float2hex(i))
h.append(float_to_hex(i))
print(h)
for i in h :
print(hex_to_float(i)," | ",hex2float(i))
转自:https://blog.csdn.net/weixin_44468956/article/details/119319582