views:

148

answers:

4

What are the best methods to "Clear the 6th bit" of an integer?

And, is your solution platform independent? (32 or 64 bit integer, etc). If not, can you give a solution that is platform independent?

Update: we don't know whether that bit is set or unset when it was given... also, any language is ok... i know of a solution that is platform independent that requires 2 operators... maybe there are various methods or simpler solutions.

Update: more clearly: clear the 6th least significant bit of an interger.

A: 

If you're sure it's already set, just subtract 64.

Update: adding the test

if((x % 128) / 64 > 0)
  x -= 64;

As far as I can see right now, this doesn't make any assumptions about the platform or language support.

ahmadabdolkader
i think cannot be sure it is already set.
動靜能量
or 32 if you think that the low bit is the "1st" bit rather than the "0th" bit. ;)
John Knoeller
Jian Lin makes a very good point, you would have to check if the 6th bit is already set. Yours was my first thought too.
drachenstern
This does both a modulo and a division to check if a bit is already set, when C and C++ already have bit manipulation operators that don't require that knowledge.
swestrup
Yes, what you noticed is obvious. This method was meant as an alternative. Try to think how to clear the bit without using bitwise operators.
ahmadabdolkader
+8  A: 

x & (~(1 << 6))

GregS
wait a second, since 1 << 1 is the 2nd bit, so won't we need 1 << 5 instead of 1 << 6?
動靜能量
Yes, but everybody assumes that you started counting on bit 0
Gonzalo
A: 

Perhaps this in c?

value&~(1<<6)
spender
+3  A: 

x&= ~(1 << 5)

MSN