Big Endian: все, что вы должны знать о порядке байтов
Big endian
Big endian is a format for representing numbers in computer systems and network protocols, where the most significant byte of a number is stored in the least significant memory address.
To better understand what big endian is, let's consider an example. Suppose we have a 4-byte integer 0x12345678 that we want to represent in memory. In the big endian format, the most significant byte will be stored in the least significant memory address. Here's how it would look:
| Address | Value |
|---|---|
| 0x0000 | 0x12 |
| 0x0001 | 0x34 |
| 0x0002 | 0x56 |
| 0x0003 | 0x78 |
Here we can see that the most significant byte 0x12 is stored in the smallest address 0x0000, and the least significant byte 0x78 is stored in the largest address 0x0003.
Now let's consider a C code example that demonstrates various operations related to big endian:
#include <stdio.h>
int main() {
unsigned int num = 0x12345678;
unsigned char* ptr = (unsigned char*)#
printf("Big endian representation:\n");
for (int i = sizeof(num) - 1; i >= 0; i--) {
printf("%02X ", ptr[i]);
}
return 0;
}
In this code, we declare the variable num and initialize it with the value 0x12345678. Then we create a pointer ptr that points to the address of num cast to unsigned char*, allowing us to access each byte of the number individually.
In the for loop, we iterate over the bytes of the number starting from the most significant (index sizeof(num) - 1) and ending with the least significant (index 0). Then we print the byte values in hexadecimal format using the printf function with the formatting %02X, which allows us to display byte values as two-digit numbers with a leading zero if necessary.
When we compile and run this code, it will output the hexadecimal representation of the number 0x12345678 in big endian format:
Big endian representation:
12 34 56 78
As we can see from the output, the bytes of the number are printed in the order from most significant to least significant, which corresponds to the big endian format.
Big endian is used in certain processor architectures such as IBM PowerPC, SPARC, and Motorola 68000. Additionally, some network protocols like TCP/IP and Ethernet also use big endian for representing numbers.
In conclusion, big endian is a format for representing numbers where the most significant byte is stored in the least significant memory address. We've looked at a C code example demonstrating the usage of big endian numbers and discussed some examples of processor architectures and network protocols that use this format.