#include <stdio.h>
/*
小端模式
数据的低位放在低地址空间,数据的高位放在高地址空间
大端模式
数据的高位放在低地址空间,数据的低位放在高地址空间
*/
bool IsLittle()//判断主机序是否为小端
{
short a = 0x0001;//小数据为0x01,高数据为0x00
return *(char*)&a == 0x01; //低地址放小数据
}
long Htonl(long a)
{
long b = 0;
/*
小端 从低地址
*/
if (!IsLittle())//大端
return a;
for (int i = 0; i < sizeof(a); i++)//小端:0x12345678->0x78563412
{ //处理单位为字节,1字节8位
// b 左移 把 低地址转成高地址
b = (b << 8) | (a & 0xff);
a >>= 8;
}
return b;
}
long Ntohl(long a) {
long b = 0;
if (!IsLittle()) return a;
// 实现都一样
for (int i = 0; i < sizeof(a); i++)//0x 78 56 34 12 -> 0x 12 34 56 78
{
b = (b << 8) | (a & 0xff);
a >>= 8;
}
return b;
}
typedef unsigned short int uint16;
typedef unsigned long int uint32;
#define BigLittleSwap32(A) ((((uint32)(A) & 0xff000000) >> 24) | (((uint32)(A) & 0x00ff0000) >> 8) | (((uint32)(A) & 0x0000ff00) << 8) | (((uint32)(A) & 0x000000ff) << 24))
int main()
{
//读数据永远是从低地址开始的!!!
// 00000000 00000000 00000000 00000004
// 00 00 00 04
// 低地址 -> 高地址
// 04 00 00 00
int a = 4;
/*
78 56 34 12
Htonl () ->
12 34 56 78
*/
printf("%x\n", Htonl(0x12345678));
printf("%x\n", BigLittleSwap32(0x12345678));
printf("%x\n", BigLittleSwap32(0x78563412));
printf("%x\n", Ntohl(0x78563412));
return 0;
}
06-01
2600