Turning off a bit

Started by
2 comments, last by Arek the Absolute 21 years, 5 months ago
I feel stupid that I can''t seem to figure this out, but how do I turn off just one bit in a larger number? For example: If I have the number 00110001 (49) and I want to set bit 2 to 1, I know I can just use the inclusive or (|) with 00000100 (4) and it ends up 00110101 (53), which is what I want. What if I want to do it the other way around though? What if I wanted to, say, turn the first bit off instead? How would I turn 00110001 (49) to 00110000 (48)? I''ve tried using ^, but that has the nasty habit of switching the bit from on to off AND from off to on. Is there any way I can turn it OFF only, and leave it alone if it''s already on? It''s easy the other way around, and it annoys me that I can''t find a way here. I could just do if ((number&(1<<bit)) == (1<<bit)) number -= 1<<bit; but that seems... well... sloppy, compared to something like number |= 1<<bit; Sorry if there''s any typos in my binary, I hope you can get the point anyway. =P -Arek the Absolute
-Arek the Absolute"The full quartet is pirates, ninjas, zombies, and robots. Create a game which involves all four, and you risk being blinded by the sheer level of coolness involved." - Superpig
Advertisement
set: x |= mask;
clear: x &= ~mask;
Wow, that was fast! Anyway, thanks a million. I''m not sure why I missed that.

-Arek the Absolute
-Arek the Absolute"The full quartet is pirates, ninjas, zombies, and robots. Create a game which involves all four, and you risk being blinded by the sheer level of coolness involved." - Superpig
You could do it by applying a not on the bit. This turns it off.

00000001 NOT 1 = 00000000

The nightmare travels across the cosmos with his burning mane. The trail of ash that is produced.

?Have a nice day!?

This topic is closed to new replies.

Advertisement