Bit Spreading Interleave Bits with Zeros

Code

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

uint16_t spread_bits(uint8_t val) {
    // Your logic here

    // Using a temp var, create the new 2-bit value, move it i*2 positions over to position it at correct spot in the 16-bit var, OR the temp with the result:
    // temp = 0x00 | (1U & (val >> i));
    // temp <<= (i * 2);
    // result |= temp;
    // First approach; can cut out temp and directly apply all operations to 'result' as seen below
    
    uint16_t result = 0U;

    for(int i = 0; i < 16; i++){
        result |= ((0x00 | (1U & (val >> i))) << (i * 2));
    }

    return result;
}

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