Compress Interleaved Bits Reverse Bit Spreading

Code

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

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

int main() {
    uint16_t val;
    scanf("%hu", &val);

    uint8_t result = compress_bits(val);
    printf("%u", result);
    return 0;
}

Solving Approach

  • Bits in val are at positions 0, 2, 4, 6, 8, 10, 12, 14.
  • Loop through i = 0 to 7 to extract each of these bits: (val >> (2*i)) & 1.
  • Place the extracted bit into the correct position of result: result |= (bit << i).
  • Return the reconstructed original 8-bit number.

 

 

Upvote
Downvote
Loading...

Input

20548

Expected Output

202