#include <stdio.h>
#include <stdint.h>
#define MASK1(value) (value & (0x000000FF))
#define MASK2(value) (value & (0x0000FF00))
#define MASK3(value) (value & (0x00FF0000))
#define MASK4(value) (value & (0xFF000000))
uint32_t convert_endian(uint32_t value) {
// Write logic to swap bytes
uint32_t result = 0;
result = (MASK1(value) << 24) | (MASK2(value) << 8) + (MASK3(value) >> 8) + (MASK4(value) >> 24);
return result;
}
int main() {
uint32_t val;
scanf("%u", &val);
printf("%u", convert_endian(val));
return 0;
}
Solving Approach
/*
Swap bytes problem in disguise
Example 1:
Input: 305419896
Output: 2018915346
0x12_34_56_78 -> 0x78_56_34_12
78
56
34
12
Plan:
- extract each byte using masks
- move the bytes to the required position using right shift
- return the result
Mask 1: 0x00_00_00_FF
Mask 2: 0x00_00_FF_00
Mask 3: 0x00_FF_00_00
Mask 4: 0xFF_00_00_00
1st byte will be shifted to the left by 24
2nd byte by 8
3rd byte to right by 8
4th byte shift to right by 24
*/
Input
305419896
Expected Output
2018915346