编程语言
首页 > 编程语言> > python不用struct 十六进制转换float

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

标签:十六进制,struct,python,pow,mStr,int,ret,binaryStr,hexStr
来源: https://blog.csdn.net/weixin_44468956/article/details/119319582