Compress Interleaved Bits Reverse Bit Spreading

Code

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

uint8_t compress_bits(uint16_t val) {
    val &= 0x5555;                // Binary: 0101 0101 0101 0101

    val = (val | (val >> 1)) & 0x3333; // Binary: 0011 0011 0011 0011

    val = (val | (val >> 2)) & 0x0F0F; // Binary: 0000 1111 0000 1111

    val = (val | (val >> 4)) & 0x00FF; // Binary: 0000 0000 1111 1111
    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