Bit Spreading Interleave Bits with Zeros

Code

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

uint16_t spread_bits(uint8_t val) {
    // Your logic here
    uint16_t res_out;
    for(int i = 0; i < 8; i++){
        uint8_t bit = !!(val & (1 << i)); // this extracts the bit at ith position and places it in the bit variable
        // (1 << i) -> usual bitmask, remember, this is the bitmask, and [x * (1<<i), where * represents any operation like] is an expression that represents the operation on the uint x!
        // val & (1<<i) -> used to check if the bit is set or not
        // !! -> common C idiom that converts non-zero values to 1 and keeps 0 as 0
        res_out |= bit << (2*i); // this places the bit at the ith position at its respective position in the interleaved result
    }

    return res_out;
}

int main() {
    uint8_t val;
    scanf("%hhu", &val);

    uint16_t result = spread_bits(val);
    printf("%u", result);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

202

Expected Output

20548