自写函数实现
#include<iostream>
using namespace std;
unsigned int fun1(unsigned int a)
{
unsigned int b = 0;
*(char *)(unsigned int(&b)) = *(char *)(unsigned int(&a) + 3);
*(char *)(unsigned int(&b) + 1) = *(char *)(unsigned int(&a) + 2);
*(char *)(unsigned int(&b) + 2) = *(char *)(unsigned int(&a) + 1);
*(char *)(unsigned int(&b) + 3) = *(char *)(unsigned int(&a));
cout << b << endl;
cout << 0x44332211 << endl;
return b;
}
unsigned int fun2(unsigned int a) {
unsigned int y=0;
((char*)&b)[0] = ((char*)&a)[3];
((char*)&b)[1] = ((char*)&a)[2];
((char*)&b)[2] = ((char*)&a)[1];
((char*)&b)[3] = ((char*)&a)[0];
cout << b << endl;
cout << 0x44332211 << endl;
return b;
}
int main()
{
fun1(0x11223344);
fun2(0x11223344);
return 0;
}
思路
以unsigned int类型为例,其变量占用四个字节内存空间,假设a=0x11223344,大端存储,占用空间0x10~0x13,b占用空间0x20~0x23,则让0x20空间内容等于0x13空间内容,0x21空间内容等于0x12空间内容,0x22空间内容等于0x11空间内容,0x23空间内容等于0x10空间内容即可。
代码说明
fun1()中,unsigned int(&a)是取a的首字节内存地址,并强制转化为unsigned int类型数据,后面加3是得到a最后一个字节的地址, 即(unsigned int(&a) + 3),对这部分进行char *转换,是将其转化为一个char类型的指向,再其前面加 * 是取该地址的内容。
fun2()中,((char*)&b)[]类似。
移位法及库函数法
参考:大端模式和小端模式