#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
int main()
{
//cout << "Hello world!" << endl;
int n=0x5678;
cout << hex << n << endl;
//method 1
char* hbyte=(char *)&n;
char* lbyte=hbyte+1;
char temp=0;
temp=*hbyte;
*hbyte=*lbyte;
*lbyte=temp;
cout << hex << n << endl;
//method 2
unsigned int x=0x5678; //一定要是unsigned ,无符号右移是逻辑右移
unsigned int y=x; //有符号右移是符号右移
cout << "................" << endl;
x= ( ((x&0xFFFF) >> 8) | ((y&0xFF) << 8) );
cout << hex << x << endl;
//method 3
union test
{
unsigned short m;
unsigned char s[2];
};
union test t;
t.m=0x5678;
cout << "..................." << endl;
cout << sizeof(t) << endl;
cout << hex << t.m << endl;
//cout << hex << (unsigned int)t.s[0] << endl;
//cout << hex << (unsigned int)t.s[1] << endl; //这里一定要有强制转换
printf("%X\n",t.s[0]);
printf("%X\n",t.s[1]);
t.s[0]=t.s[0]^t.s[1];
t.s[1]=t.s[0]^t.s[1];
t.s[0]=t.s[0]^t.s[1];
cout << hex << t.m << endl;
//数据交换还可以这样
t.s[0] = t.s[0] + t.s[1];
t.s[1] = t.s[0] - t.s[1];
t.s[0] = t.s[0] - t.s[1];
cout << hex << t.m << endl;
//t.l
system("pause");
return 0;
}
交换字节
最新推荐文章于 2023-05-21 20:41:33 发布