All submissions

Bit Spreading Interleave Bits with Zeros

Code

//
// Created by James Gallegos on 9/23/25.
//




// 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



#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>   // for PRIu16 portable printf macro

// Spread the bits of an 8-bit value so each original bit i goes to bit (2*i) in the 16-bit result.
// Example: val=0xFF -> result=0x5555 (all even bits set).
uint16_t spread_bits(uint8_t val) {
    uint16_t out = 0;                 // we'll build the 16-bit answer here

    // Cycling thru the given value
    for (uint8_t i = 0; i < 8; i++) {
        // shift current bit all the way to the right, then mask everything by ANDing w/ 0x1
        uint16_t bit_i = (val >> i) & 0x1u;
        // shift left by 2*i to place in correct spot(2*i+1 for odd placement)
        out |= (uint16_t)(bit_i << (2 * i));
    }
    return out;
}

int main() {
    uint8_t val;
    // %hhu reads an unsigned 8-bit quantity portably
    if (scanf("%hhu", &val) != 1) {
        return 0; // guard: no input read
    }

    uint16_t result = spread_bits(val);

    // Use PRIu16 for portable printing of uint16_t across platforms
    printf("%" PRIu16, result);
    return 0;
}

Solving Approach

 

 

 

Loading...

Input

202

Expected Output

20548