Bit Spreading Interleave Bits with Zeros

Code

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

uint16_t spread_bits(uint8_t val) {
    // Your logic here
    uint16_t result = 0;
    for (int i = 0; i < 8; i++){
        if (val & (1<<i)){
            result |= (1<<(i*2));
        }
        else{
            result &= (~(1<<(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

  1. First create a 16 bit register with all values set to zero, we have already solved for all odd positions this way.
  2. Now Check all the values of the 8bit register, If they are set, set the corresponding even value in the 16 bit register, if not clear the corresponding bit in the 16 bit register.

 

 

Upvote
Downvote
Loading...

Input

202

Expected Output

20548