91. Bit Spreading Interleave Bits with Zeros

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

// Spread bits with 0s between them (interleave into 16-bit)
uint16_t spread_bits(uint8_t val) {
    uint16_t result = 0;

    for (int i = 0; i < 8; i++) {
        uint8_t bit = (val >> i) & 1;           // Extract i-th bit
        result |= (bit << (2 * i));             // Place in 2*i position
    }

    return result;
}

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

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

Why It Matters in Firmware?

  • Used in memory-mapped IO where each bit maps to separate hardware line
  • Helps in hardware simulators or DSP where spreading reduces crosstalk
  • Used in Morton code (Z-order curves) for spatial indexing

Logic Summary

  • For each bit in the input
  • Shift it to its new “spread” location (multiply position by 2)
  • OR it into the final 16-bit result
     
Loading...

Input

202

Expected Output

20548