Bit Spreading Interleave Bits with Zeros

Code

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

/*
In some protocols or hardware applications (e.g. graphic rendering, signal encoding), bit spreading or interleaving is used to insert 0s between the bits of a value for purposes like data alignment or transmission.

You are given an 8-bit number, and your task is to:

Spread the bits such that each bit is followed by a 0
The result will be a 16-bit number where each original bit occupies even positions (0, 2, 4&#8230;)
All odd positions are 0s
*/
uint16_t spread_bits_test(uint8_t val)
{
    uint16_t res;
    for(int i=7;i>=0;i--){
        // l&#7845;y ph&#7847;n t&#7917; LSB
        uint8_t lsb = (val>>i)&1;
        // t&#7841;o ra 2 kho&#7843;ng tr&#7889;ng b&#234;n ph&#7843;i
        res <<= 2;
        // add 0 v&#224;o b&#234;n tr&#225;i
        res |= (0<<1);
        // add bit g&#7889;c v&#224;o b&#234;n ph&#7843;i
        res |= lsb;
    }
    
    return res;
}
uint16_t spread_bits_mask(uint8_t val)
{
    uint16_t res = val;
    // shift
    for(int shift = 4;shift>0;shift>>=1){
        // mask
        uint16_t mask = 0;
        for(int i=0;i<16;i++){
            // block
            uint16_t block = i/shift;
            if((block&1)==0){
                mask |= (1<<i);
            }
        }
        res = (res|(res<<shift))&mask;
    }
    
    return res;
}
uint16_t spread_bits_mask_fast(uint8_t val)
{
    uint16_t res = val;
    // shift
    for(int shift = 4;shift>0;shift>>=1){
        // mask
        uint16_t mask = 0XFFFF/((1<<shift)+1);
        res = (res|(res<<shift))&mask;
    }
    
    return res;
}

int main()
{
    uint8_t val;
    scanf("%hhu", &val);

    uint16_t result = spread_bits_mask_fast(val);
    printf("%u", result);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

202

Expected Output

20548