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

John Doe Permalink
July 01, 2009, 15:06

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

Bill Permalink
October 20, 2010, 14:28

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

y = x & 0xFFFFFFE

(at least for 32-bit values)

Tom Kha Gai Permalink
October 20, 2010, 16:36

I do not see any problem.

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

jsc42 Permalink
October 21, 2010, 12:52

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.

January 08, 2017, 00:23

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

John C. Permalink
October 21, 2010, 12:54

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.

Eralp Permalink
March 11, 2014, 21:31

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.

January 08, 2017, 00:24

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

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

August 05, 2015, 09:13

Right, turning off the rightmost bit is this

x = n & (~1)

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

January 08, 2017, 00:25

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

January 08, 2017, 00:22

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

Reply To This Comment

(why do I need your e-mail?)

(Your twitter handle, if you have one.)

Type the word "floppy_143": (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.