Extract Even Bits Only from 32-bit Register

Code

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

uint32_t extract_even_bits(uint32_t reg) {
    uint8_t itr = 0;
    uint32_t result = 0;
    while (itr < 16) {
        result |= (((1 << (itr*2) ) & reg) >> itr);
        itr++;
    }
    return result;
}

int main() {
    uint32_t reg;
    scanf("%u", &reg);
    printf("%u", extract_even_bits(reg));
    return 0;
}

Solving Approach

This program extracts all even-positioned bits (positions 0, 2, 4, ..., 30) from a 32-bit unsigned integer and packs them into a new integer, forming a sequence. Each extracted bit is placed in consecutive positions (0, 1, 2, ...) in the result, effectively compressing the even bits into a compact form. The main function reads an input number, calls the extraction function, and prints the result. The corrected logic ensures each even bit is properly isolated and packed.

 


 

 

 

Upvote
Downvote
Loading...

Input

85

Expected Output

15