Bit Spreading Interleave Bits with Zeros

Code

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

// Spread a 4-bit nibble into a byte by inserting 0 bits between bits,
// so nibble bits land at positions 6,4,2,0 of the result byte.
static inline uint8_t dilate4to8(uint8_t x) {
    x &= 0x0F;                 // keep only lower 4 bits
    x = (x | (x << 2)) & 0x33; // 0b00110011: separate into pairs
    x = (x | (x << 1)) & 0x55; // 0b01010101: insert zeros between each bit
    // Now bits occupy positions 0,2,4,6 -> exactly what we need.
    return x;
}

uint16_t spread_bits(uint8_t val) {
    uint8_t upper = dilate4to8(val >> 4);   // becomes high byte
    uint8_t lower = dilate4to8(val & 0x0F); // becomes low byte
    return ((uint16_t)upper << 8) | lower;
}

int main(void) {
    uint8_t val;
    if (scanf("%hhu", &val) != 1) {
        return 1;
    }

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

202

Expected Output

20548