Bit Spreading Interleave Bits with Zeros

Code

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

uint16_t spread_bits(uint8_t reg) {
    
    uint16_t reg_result = 0;

    for(int pos = 0; pos < 8; pos++)
    {
        // get bit, shift it to end, shift left
        reg_result |= ((reg & (1U << pos)) >> pos) << 2*pos;
    }
    return reg_result;
}

/*
    ari's version:

static uint16_t spread_bits(uint8_t x)
{
    uint16_t v = (uint16_t)x;
    v = (v | (v << 4)) & 0x0F0Fu;
    v = (v | (v << 2)) & 0x3333u;
    v = (v | (v << 1)) & 0x5555u;
    return v;
}
*/

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