C语言与Lua语言实现三字节浮点数转换函数示例 - 老K的博客
C语言与Lua语言实现三字节浮点数转换函数示例
C语言实现cunsigned long int pow1(unsigned char a1,unsigned char a2){ unsigned char i; unsigned long int value=1; for(i=0;i<a2;i++) value*=a1; return value;
}
/函数名称: UR_3hex2float功能描述: 三字节浮点数转化输入参数: low--低字节middle--中字节high--高字节输出参数: 浮点数 -- float作 者: 王海强日 期: 2009、3、14版 本: V1.0调用关系: 任意算法描述:备 注: 创建/float UR_3hex2float(unsigned char low,unsigned char middle,unsigned char high){ unsigned char SignB=0,CmplSignB=0; unsigned long int temp; float mantissa; float val;
mantissa = (float)(middle * 256 + low); if(high>=128) { SignB=1; high-=128; } if(high>=64) { high=128-high; CmplSignB=1; } if((high>16) && (CmplSignB==0)) //(2∧(high-8))*middle { temp=1<<(high-16); val=(float)(mantissa*(temp*1.0f)); } else { if(CmplSignB==1) { temp=16+high; //(2∧-(high+8))*middle=middle/(2∧(high+8)) if(temp>=32) temp=31; } else temp=16-high; //(2∧-(8-high))*middle=middle/(2∧(8-high)) val= (float)(mantissa/(pow1(2,(unsigned char)temp)*1.0f)); }
if(SignB==1) //judge val<=0 { val=-val; }
return val;}
Lua语言实现luafunction pow1(a1, a2) local value = 1 for i = 1, a2 do value = value * a1 end return valueend
function UR_3hex2float(low, middle, high) local SignB = 0 local CmplSignB = 0 local temp local mantissa local val
mantissa = middle * 256 + low if high >= 128 then SignB = 1 high = high - 128 end if high >= 64 then high = 128 - high CmplSignB = 1 end if high > 16 and CmplSignB == 0 then temp = 2 ^ (high - 16) val = mantissa * temp else if CmplSignB == 1 then temp = 16 + high if temp >= 32 then temp = 31 end else temp = 16 - high end val = mantissa / (pow1(2, temp)) end
if SignB == 1 then val = -val end
return valend
函数功能
以上代码实现了将三字节浮点数转换为浮点数的功能。函数 UR_3hex2float 接收三个参数,分别代表三字节浮点数的低字节、中字节和高字节,并返回转换后的浮点数。
算法描述
该算法首先根据高字节的值判断符号位和指数位,然后根据指数位的值计算出尾数,最后将符号位、指数位和尾数组合成浮点数。
备注
以上代码仅供参考,实际应用中需要根据具体情况进行修改。
原文地址: https://www.cveoy.top/t/topic/f3Vx 著作权归作者所有。请勿转载和采集!