#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…)
All odd positions are 0s
*/
uint16_t spread_bits_test(uint8_t val)
{
uint16_t res;
for(int i=7;i>=0;i--){
// lấy phần tử LSB
uint8_t lsb = (val>>i)&1;
// tạo ra 2 khoảng trống bên phải
res <<= 2;
// add 0 vào bên trái
res |= (0<<1);
// add bit gốc vào bên phả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;
}
Input
202
Expected Output
20548