Tony54
Tony54

Reputation: 265

Bitmask and selecting even bits

I'm reading a book that states:

To select all the even bits in a 32 bit unsigned int, we can AND the number with the bitmask 0xAAAAAAAAAA, which is a 32 bit number with even bits set (0xA is a decimal 10, 1010 binary). For selecting odd bits we can AND with bitmask 0x5555555555, which is a number with all even bits set (0x5 is decimal 5, 0101 in binary)

What I don't get is how 0x or 1010 sets all even bits to 1. If you go from right to left starting from zero clearly it is the odd bits that are set. What am I missing?

Upvotes: 2

Views: 3926

Answers (2)

koldewb
koldewb

Reputation: 462

The left to right thing is where you make a mistake.

See what happens when you actually do it:

In binary 32-bits:

your number: 1111 1111 1111 1111 1111 1111 1111 1111

Mask:        1010 1010 1010 1010 1010 1010 1010 1010

result:      1010 1010 1010 1010 1010 1010 1010 1010

The first bit (from the right!!!) is odd, and will be not get set when using 0xAAAAAAAAAA as bitmask using the AND operator. Only the even bits will get set. Always start at the least significant bit.

Upvotes: 1

Sagar Jain
Sagar Jain

Reputation: 7941

You need to count the position of the bits from right (LSB) as first bit (Odd) and second bit (Even).

Upvotes: 0

Related Questions