#include <stdio.h>
#include <stdint.h>
#define BYTE_0_MASK (0x000000FF)
#define BYTE_1_MASK (0x0000FF00)
#define BYTE_2_MASK (0x00FF0000)
#define BYTE_3_MASK (0xFF000000)
void convert_to_big_endian(uint32_t value, uint8_t arr[4]) {
arr[3] = value & BYTE_0_MASK;
arr[2] = (value & BYTE_1_MASK) >> 8;
arr[1] = (value & BYTE_2_MASK) >> 16;
arr[0] = (value & BYTE_3_MASK) >> 24;
}
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;
}
The current solution converts a 32-bit integer to big-endian byte order by extracting each byte using bitwise masks and shifts, then storing them in a 4-element array. The most significant byte is placed at the lowest index, and the least significant byte at the highest index, matching big-endian format. This approach is efficient for preparing data for network transmission or file storage, where byte-wise representation is required. The code avoids loops for extraction, using direct assignments for each byte, resulting in clear and fast execution.
Input
305419896
Expected Output
18 52 86 120