24. Data Transmission

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>
#include <stdint.h>

void convert_to_big_endian(uint32_t value, uint8_t arr[4]) {
    // Your code here
    uint32_t first_byte_mask = 0xFF000000;
    uint32_t second_byte_mask = 0x00FF0000;
    uint32_t third_byte_mask = 0x0000FF00;
    uint32_t fourth_byte_mask = 0x000000FF;
    arr[0] = (value & first_byte_mask) >> 24;
    arr[1] = (value & second_byte_mask) >> 16;
    arr[2] = (value & third_byte_mask) >> 8;
    arr[3] = (value & fourth_byte_mask);
}

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

Since we are extracting the bytes (every 8-bits) from a 32-bits value, we can use bitmasks to extract the values and right shifting the result accordingly; then assigning the resulting values into the byte array.

 

 

Was this helpful?
Upvote
Downvote