22. Extract Even Bits Only from 32-bit Register

Back To All Submissions
Previous Submission
Next Submission
#include <stdio.h>
#include <stdint.h>

uint16_t extract_even_fast(uint32_t x) {
    x &= 0x55555555;                 // Giữ bit: .a.b.c.d.e.f.g.h (dấu chấm là bit lẻ đã bị xóa)
    x = (x | (x >> 1)) & 0x33333333; // Dồn thành: ..ab..cd..ef..gh
    x = (x | (x >> 2)) & 0x0F0F0F0F; // Dồn thành: ....abcd....efgh
    x = (x | (x >> 4)) & 0x00FF00FF; // Dồn thành: ........abcdefgh
    x = (x | (x >> 8)) & 0x0000FFFF; // Kết quả nằm ở 16 bit thấp

    return (uint16_t)x;
}

int main() {
    uint32_t reg;
    scanf("%u", &reg);
    printf("%hu", extract_even_fast(reg));
	
	
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote