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 new_val = 0;
    for(int i=0;i<8;i++){
        uint16_t bit = (val>>i) & 1;
        new_val = new_val | (bit<<i*2);
    }
    return new_val;
}

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

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

Solving Approach

I took a 16 vit variable 'bit' to extract bits from 8 bit value one by one.
Then I ORed it with the new_val (which we want after appending 0s at the odd places) with shifted 'bit' right shifted by i*2 i.e. 0,2,4,6,8,...14.

 

 

Upvote
Downvote
Loading...

Input

202

Expected Output

20548