Bit Spreading Interleave Bits with Zeros

Code

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

uint16_t spread_bits(uint8_t val) {
    uint16_t result = 0;
    
    for (int i = 0; i < 8; i++) {
        // 1. Isolate the i-th bit using a mask (1 << i)
        // 2. Shift it to the left by 'i' additional spots to reach position 2*i
        // 3. OR it into the result
        if (val & (1 << i)) {
            result |= (1 << (2 * i));
        }
    }
    
    return result;
}

int main() {
    uint8_t val;
    // Note: %hhu is the correct format specifier for uint8_t
    if (scanf("%hhu", &val) == 1) {
        uint16_t result = spread_bits(val);
        printf("%u\n", result);
    }
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

202

Expected Output

20548