#include <stdio.h>
#include <stdint.h>
void convert_to_big_endian(uint32_t value, uint8_t arr[4])
{
arr[0] = (uint8_t)(value >> 24);
arr[1] = (uint8_t)(value >> 16);
arr[2] = (uint8_t)(value >> 8);
arr[3] = (uint8_t)(value);
}
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;
}This code is a utility for Endianness Conversion. Specifically, it takes a single 32-bit integer (which is usually stored in a single "block" in memory) and breaks it down into 4 individual bytes ordered in Big Endian format.
"Big Endian" means the Big End (the most significant part of the number) is stored at the first memory address (index 0).
In many modern computers (like those using Intel or AMD processors), numbers are stored in "Little Endian" format (backward). However, Network Protocols and Automotive UDS/CAN standards almost always require Big Endian. This code acts as the "translator" to prepare data for transmission over a network or vehicle bus.
To break the 32-bit number into 4 bytes, the code uses a "Shift and Chop" method:
value >> 24: Moves the highest 8 bits all the way to the right.value >> 16: Moves the second-highest 8 bits to the right.value >> 8: Moves the third-highest 8 bits to the right.(uint8_t) Casting: This "chops" off everything except the last 8 bits, effectively isolating one byte at a time.Suppose we have the Hexadecimal value 0x12345678 (Decimal: 305419896).
| Array Index | Operation | Binary Calculation | Hex Result |
|---|---|---|---|
arr[0] (MSB) | value >> 24 | 0x12345678 → 0x00000012 | 0x12 (18) |
arr[1] | value >> 16 | 0x12345678 → 0x00001234 | 0x34 (52) |
arr[2] | value >> 8 | 0x12345678 → 0x00123456 | 0x56 (86) |
arr[3] (LSB) | value >> 0 | 0x12345678 → 0x12345678 | 0x78 (120) |
Final Byte Array: [18, 52, 86, 120]
uint8_t arr[4] as a parameter. In C, this passes a pointer to the array, meaning the function modifies the original array created in main().Input
305419896
Expected Output
18 52 86 120