Compress Interleaved Bits Reverse Bit Spreading

Code

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

uint8_t compress_bits(uint16_t val) {
    // Your logic here
    val = val & 0x5555; // mute odd position bits
    val = (val | (val >> 1)) & 0x3333; // making groups of 2s like 00 11 00 11
    val = (val | (val >> 2)) & 0x0F0F; // making groups of 4s like 00 00 11 11
    val = (val | (val >> 4)) & 0x00FF; // making groups of 8s like 11 11 11 11
    // one can extend to 32 bits as
    //  val & 0x5555 55555
    // (val >> 1) & 0x3333 3333
    // (val >> 2) & 0x0F0F 0F0F
    // (val >> 4) & 0X00FF 00FF
    // (val >> 8) & 0x0000 FFFF

    return (uint8_t)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