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 spread_out =0;
    uint16_t bit;
    for (int i=0; i<8;i++)
    {
        bit = (val>>i)&1;
       // printf("bit is %u\n", bit);
        spread_out |= (bit<<i*2);
    }

    return spread_out;
}

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

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

Solving Approach

Init a uint16 and compute the bit equivalent of the input value shifted to the right by the loop index. Loop i over the input size and set the uint16 i*2 index as the bit equivalent to interleave with zeros

 

 

Upvote
Downvote
Loading...

Input

202

Expected Output

20548