All submissions

Code

#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;
}

Solving Approach

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:

  • MSB = 0x12
  • Next = 0x34
  • Next = 0x56
  • LSB = 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?

  • It ensures that only the lowest 8 bits are kept.
  • Even after shifting, we mask to isolate the byte cleanly.

๐Ÿ“ฆ 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.

Loading...

Input

305419896

Expected Output

18 52 86 120