Bit Spreading Interleave Bits with Zeros

Code

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

uint16_t spread_bits(uint8_t val) {
    // 1) for loop to traverse thru new 16 bit int
    // 2) inside for loop, skip two indices
    // 3) take value from original and put it in new int

    uint16_t res = 0;
    for (int i = 0; i < 16; i+=2)
    {
        res |= ((val & 1) << i);
        if (i == 0 || !(i % 2)) val >>= 1; 
    }

    return res;
}

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