#include <stdio.h>
#include <stdint.h>
void convert_to_big_endian(uint32_t value, uint8_t arr[4]) {
arr[0] = (value >> 24) & 0xFF; // Most significant byte
arr[1] = (value >> 16) & 0xFF;
arr[2] = (value >> 8) & 0xFF;
arr[3] = value & 0xFF; // Least significant byte
}
int main() {
uint32_t value;
uint8_t arr[4];
scanf("%u", &value);
convert_to_big_endian(value, arr);
for (int i = 0; i < 4; i++) {
printf("%u", arr[i]);
if(i<3){
printf(" ");
}
}
return 0;
}
Let's walk through the detailed explanation of how to convert a 32-bit value into a 4-byte array in big-endian format, which is essential for consistent data transmission across platforms.
๐งฉ What Is Big-Endian?
In big-endian format, the most significant byte (MSB) comes first. This is the standard used in many network protocols (like TCP/IP) and some processors.
For example, if you have a 32-bit value:
value = 0x12345678
The bytes are:
0x12
0x34
0x56
0x78
So in big-endian order, the byte array should be:
arr[0] = 0x12
arr[1] = 0x34
arr[2] = 0x56
arr[3] = 0x78
๐ ๏ธ Bitwise Extraction Logic
To extract each byte from a 32-bit value, we use bitwise shifting and masking:
arr[0] = (value >> 24) & 0xFF; // Extract bits 31โ24
arr[1] = (value >> 16) & 0xFF; // Extract bits 23โ16
arr[2] = (value >> 8) & 0xFF; // Extract bits 15โ8
arr[3] = value & 0xFF; // Extract bits 7โ0
Why & 0xFF
?
๐ฆ Real-World Use Case
Imagine you're sending sensor data from an ESP32 to a Raspberry Pi over UART or SPI. If the Pi expects big-endian format, but the ESP32 is little-endian, you must convert the data before transmission. Otherwise, the Pi will misinterpret the bytes.
๐ Example Walkthrough
Letโs say:
uint32_t value = 0x01020304;
Binary representation:
00000001 00000010 00000011 00000100
Using the function:
arr[0] = (value >> 24) & 0xFF; // 0x01
arr[1] = (value >> 16) & 0xFF; // 0x02
arr[2] = (value >> 8) & 0xFF; // 0x03
arr[3] = value & 0xFF; // 0x04
Output:
arr = {1, 2, 3, 4}
Also note: when you pass an array to a function, youโre actually passing a pointer to its first element. So any modification made to arr inside the function will reflect in the main() function โ because both refer to the same memory.
Input
305419896
Expected Output
18 52 86 120