方法一:
#include <stdio.h></span>
int getdata(char *buf, int n) //buf[0]是高位字节, buf[2]是低位字节</span>
{
int ret = 0;
short s = (short)buf[0]; //将buf[0]符号扩展为两个字节,即ps[1],ps[0]
char *ps = (char *)&s;
char *pret = (char *)&ret;
// 将buf[2],buf[1],ps[0],ps[1] 拼接为int的四个字节
pret[0] = buf[2];
pret[1] = buf[1];
pret[2] = ps[0];
pret[3] = ps[1];
return ret;
}
int main()
{
int result = 0;
char a[3] = { 0x01, 0x01, 0x01 };
char b[3] = { 0xf0, 0x01, 0x01 };
result = getdata(a, 3);
printf("%d\n", result);
result = getdata(b, 3);
printf("%d\n", result);
getchar();
}
方法二
int getdata(unsigned char *buf, int n)
{
<span style="white-space:pre"> </span>int ret = buf[0]<<16; // buf[0]为高位, 左移16位,相当于buf[0]*2^16
<span style="white-space:pre"> </span>ret|= buf[1] << 8; //相对于bu