交换字节

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值