Compress Interleaved Bits Reverse Bit Spreading

Code

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

uint8_t compress_bits(uint16_t val) {
    uint8_t sub = 0;
    uint8_t bit = 1;
    uint8_t rev = 0;
    
    // Compress value   
    for (int i = 0; i < 7; i++) {
        sub |= (val >> 2*i) & 1;
        sub <<= 1;   
    }
    // Shift last step back not to capture non-meaning value
    sub |= (val >> (2*7)) & 1;

    // Reverse compressed value
    for (int i = 0; i < 8; i++) {
        rev |= ((sub & bit) >> i) << (7-i);
        bit <<= 1;
    }
    return rev;
}

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