python不用struct 十六进制转换float

自用记录

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值