自用记录
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;
public static double hexstr2ieee745(String hexStr){
StringBuffer binaryStr = new StringBuffer();
for(int i=0;i< hexStr.length();i+=2){
String a = hexStr.substring(i,i+2);
int c = Integer.parseInt(a,16);
String item = String.format("%08d",Integer.parseInt(Integer.toBinaryString(c)));
binaryStr.append(item);
}
int n = Integer.parseInt(binaryStr.substring(1,9),2);
String mStr = binaryStr.substring(9,binaryStr.length()-1);
double sum = 0;
for(int i =1;i<=mStr.length();i++){
if(mStr.charAt(i-1)=='1'){
sum = sum+Math.pow(0.5,i);
}
}
double a =( Math.pow(2,n-127))*(1+sum);
return a;
}
转自:https://www.cnblogs.com/bingoj/p/11148305.html
互转
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/cherry1307/article/details/97624014