We know that the network byte order is the TCP/IP layer protocol that defines the byte order as Big-endian.
Therefore, network programming is destined to use the small end to big endian for the byte order.
A detailed view of the big-endian and small-end modes: a blog
The 32bit wide number of 0x12345678 in Little-endian mode CPU memory (assuming that it is stored from the address 0x4000) is as follows:
Memory address 0x4000 0x4001 0x4002 0x4003
Storage content 0x78 0x56 0x34 0x12
In Big-endian mode, the CPU memory is stored in the following way:
Memory address 0x4000 0x4001 0x4002 0x4003
Storage content 0x12 0x34 0x56 0x78 judgment is big or small end small end to the big-endian conversion 1. Judging whether it's big-endian or small- end
Idea: Convert the int type to a char type to determine the lowest byte.
int main (void)
{short
int a = 0x1234;
Char *p = (char *) &a;
if (*p = 0x34)
cout<< "Little endian" <<endl;
else
cout<< "Big endian" <<endl;
return 0;
}
int main (void)
{short
int a = 0x1234;
char x0, X1;
x0 = ((char *) &a) [0];
X1 = ((char *) &a) [1];
Small end: Low address holds low byte
if (x0 = = 0x34)
cout<< "Little endian" <<endl;
else
cout<< "Big endian" <<endl;
return 0;
}
2. Small-end to big-endian conversion
Use shift. for 32-bit:
Maximum byte: Move right 24 bits
Sub-high byte: Move right 8 bits
Sub low byte: Shift left 8 bits
Minimum byte: Shift left 24 bits
uint32_t reversebytes_uint32t (uint32_t value) {
return (value & 0x000000ffu) << 24 | (Value & 0x0000ff00u) << 8 |
(Value & 0x00ff0000u) >> 8 | (Value & 0xff000000u) >>;
}
for 64-bit:
First, the high 32 bit to small end mode
Low 32-bit turn-small end mode
Then swap the high 32-bit and low 32-bit
First, the 64-bit low 32-bit into the small-end mode, and then the 64-bit high 32 bits into the small-end mode
//In the original low 32-bit to high 32-bit, the original high 32 bits placed to low 32-bit
uint64_t reversebytes_uint64t ( uint64_t value) {
uint32_t High_uint64 = uint64_t (reversebytes_uint32t (uint32_t (value))); Low 32 bits turn into small end
uint64_t Low_uint64 = (uint64_t) reversebytes_uint32t (uint32_t (value >>)); High 32 bits turn into small end
return (High_uint64 << +) + Low_uint64;