Compress Interleaved Bits Reverse Bit Spreading

Code

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

uint8_t compress_bits(uint16_t val) {
    
    // Step 1: Mask even bits
    // 0x5555 is 01010101 01010101 in binary
    val &= 0x5555;

    // Move bits 8, 10, 12, 14 down by 4 to meet bits 0, 2, 4, 6 halfway
    // Result: ..ab..cd ..ef..gh
    val = (val | (val >> 1)) & 0x3333; 

    // Move groups of 2 down by 2
    // Result: ....abcd ....efgh
    val = (val | (val >> 2)) & 0x0F0F;
    
    // Move the high byte down by 4 to join the low byte
    // Result: ........ abcdefgh
    val = (val | (val >> 4)) & 0x00FF;

    return val;
}

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

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

20548

Expected Output

202