在项目开发中,从传感器读到2个字,高字在前,低字在后,本文用两种方法,将两个字顺序交换,转换为32位整数。
方法一:用联合体
方法二:位移动
#include <QApplication>
#include <QDebug>
union int32Split
{
int int32Value; // 32位整数
struct
{
unsigned short word0;
unsigned short word1;
} sInt32Values;
unsigned short Uint16Array[2];
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
int32Split c,c2;
c.Uint16Array[1]=65535;//
c.Uint16Array[0]=65533;
qDebug()<<c.int32Value;
//-------------------
c2.int32Value=-3;
qDebug()<<c2.Uint16Array[1];
qDebug()<<c2.Uint16Array[0];
//-------------------
int c3,c4;
c3=65535<<16;//左移16位
c4=c3 | 65533;//位或运算
qDebug()<<c4;
//------------------
unsigned short d1=c4>>16;//右移16位
unsigned short d2=c4 & 0xffff;//位与运算
qDebug()<<d1;
qDebug()<<d2;
return a.exec();
}