unsigned short unCharToUnShort(unsigned char* pBuf)
{
unsigned short result = 0;
result = (short)pBuf[0]*256;
result += (short)pBuf[1];
return result;
}
unsigned int unCharToUnInt(unsigned char* pBuf)
{
unsigned int result = 0;
result = (short)pBuf[0]*256*256*256;
result += (short)pBuf[1]*256*256;
result += (short)pBuf[2]*256;
result += (short)pBuf[3];
return result;
}
以上两个函数是把unsigned char*转换为unsigned short或unsigned int,数据的存放方式为高字节在前,低字节在后,比如无符号短整型256是0x01 0x00。我们通过依次获取低位的数据然后乘以0xFF,来获取低位所代表的整数值,然后再把各个位的值相加,得出最终需要的无符号整形值。其中把一个字节强转为short型,就是为了获取该字节的无符号整型值,因为一个short值占两个字符,我们这样强转,其实只用了short高位的那一个字节。
void unShortToUnChar(unsigned char* pBuf,unsigned short iValue)
{
pBuf[0] = (unsigned char)(iValue>>8);
pBuf[1] = (unsigned char)(iValue);
}
void unIntToUnChar(unsigned char* pBuf,unsigned int iValue)
{
pBuf[0] = (unsigned char)(iValue>>24);
pBuf[1] = (unsigned char)(iValue>>16);
pBuf[2] = (unsigned char)(iValue>>8);
pBuf[3] = (unsigned char)(iValue);
}
以上两个函数作用是把无符号整形转换为unsigned char型。所使用的方式是把整型值右移8的倍数,然后取高位强转为unsigned char后赋值给我们的unsigned char数组中的各个字节。
在做无符号数据类型和有符号数据类型转换的时候方式有很多,此处介绍的是我觉得比较简单且易懂的,代码已在VS和linux下测试通过。大家如果有更好的方式,欢迎跟帖交流,我好对本文章进行更新,方便其它同仁学习。