Bit Spreading Interleave Bits with Zeros

Code

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

uint16_t spread_bits(uint8_t val) {
    uint16_t result = 0;

    for( int i = 0; i < 8; i++){
        uint16_t bit = (val >> i) & 1;
        result |= (bit << (2 * i));
    }
    return result;
}

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

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

Solving Approach

  • Initialize result = 0.
  • Loop through each bit of the 8-bit input (i = 0 to 7).
  • Extract the i-th bit: (val >> i) & 1.
  • Place it in the even position of 16-bit result: bit << (2 * i).
  • OR it with result: result |= ....
  • Return result.

 

 

Upvote
Downvote
Loading...

Input

202

Expected Output

20548