freescale單片機(jī)單精度浮點(diǎn)與16進(jìn)制與ascii之間的轉(zhuǎn)換
float BallData[8] = {-8.925133};
本文引用地址:http://m.butianyuan.cn/article/201611/322587.htmunsigned char *f2char;
unsigned char ControlData[64];
void float2uchar2ascii(void)
{
unsigned char i = 0;
f2char = &BallData;//float to unsiged char[]
//8個(gè)floatd對應(yīng)于32個(gè)unsigned char,所以f2char為32位
//f2char[32]={0xC10EDC58,0xC10EDC58,0xC10EDC58,0xC10EDC58,...,0xC10EDC58}
for(i=0;i<32;i++)
{
ControlData[2*i ] = f2char[i]/16+(f2char[i]/16>9?55:48);//unsigned char to ascii char
ControlData[2*i+1] = f2char[i]+(f2char[i]>9?55:48);
//本例中,f2char[0]=0xC1,要把它轉(zhuǎn)換為ascii碼字符串首先要得到高四位,然后得到低四位
//如果四位的值大于9,則應(yīng)轉(zhuǎn)換為字母a~f,否則應(yīng)轉(zhuǎn)換為0~9
//字母的應(yīng)該在結(jié)果上+55,因?yàn)閍的ascii碼為65,基數(shù)為10,于是加55
//數(shù)字的應(yīng)該在結(jié)果上+48,因?yàn)?的ascii碼為48,基數(shù)為00,于是加48
}
}
//---將ascii碼字符串轉(zhuǎn)換成單精度浮點(diǎn)
unsigned char ControlData[64]={"C10EDC58"};
float BallData[8];
void asciistring2single(void)
{
unsigned char i=0,k=0;
unsigned char temp[4];
for(i=0;i<64;i++)
{
temp[i]=ControlData[i%4];
if(i%4==3)
{
BallData[k++]=(*((float*)temp));
}
}
}
//---將16進(jìn)制與float之間的轉(zhuǎn)換
union f_to_char
{
uchar chr[4];
float ft0;
} test;//定義一個(gè)union,直接對test.float操作,即從chr[4]中得到16進(jìn)制的數(shù)組;反之亦然
test.ft0=3.14;//→chr[4]={0x40,0x48,0xF5,0xC3};
評論