# Low Level Bit Hacks You Absolutely Must Know

You're viewing a comment by John Doe and its responses.

Sorry to be a party crusher, but you've got a mistake (at least one, I stopped reading.)

=========================================
Bit Hack #6. Turn off the rightmost 1-bit.

y = x & (x-1)
=========================================

Plain wrong. Any X ending with xxx10, when ANDed with (x-1), which obviously ends with xxx01, gives xxx00, ie. a number whose LAST TWO BITS ARE 0.

2d & 1d = 0
10d (0xA) & 9d (0x9) = 8.

Sorry.

### Comment Responses

Isn't the answer for Bit Hack #6 simply:

y = x & 0xFFFFFFE

(at least for 32-bit values)

I do not see any problem.

xxx10 => xxx00, so the rightmost bit is 0 after that, as advertised.

The problem is with the word 'rightmost' in the title. Like you, I initially assumed that it meant the final bit in the pattern; but what it is intended to mean is "Reset the first found bit that has a value of one when scanning from right to left", but that is a mouthful!

The affected bit in your example of 'xx10' is the '1' between the 'xx' and '0', which (as you correctly point out) is the bit that gets changed to 'xx00'. Rather than being an error, that is the intention of the hack.

No, the problem is that you and John Doe are stupid. There is nothing in the least ambiguous about "the rightmost 1-bit".

I had to go back and read Bit Hack#6 again to check, but it DOES do what it says - it turns off the *rightmost 1 bit* (that is, the last binary '1' when reading left to right), which is not necessarily the *rightmost bit* of the number.

Grammatically it isn't clear that 1 is not count but the property of the bit. I mean it could mean "turns off rightmost n bits", it is here clear that n is count, in case of 1 we can't be sure about that.

I understood it from the context but I see what 'John Doe' says.

"Grammatically it isn't clear that 1 is not count but the property of the bit."

God that's funny. Talk about grammatically unclear ...

Right, turning off the rightmost bit is this

x = n & (~1)

2 & ~1 = 2
3 & ~1 = 2

No, stupid, this is about turning off the rightmost *1-bit*.

Sorry, but you're an idiot ... turning off the rightmost 1-bit of 10 yields 00 ... duh.