0

I did it like that: How do you set, clear and toggle a single bit in C?.

Clearing a bit

Use the bitwise AND operator (&) to clear a bit.

number &= ~(1 << x);

That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.

It works fine with signed integer types, but doesn't work with unsigned integer (e.g. UInt32). Compiler says that it's impossible to do that kind of operation to unsigned types. How to deal with unsigned numbers to clear one bit then ?

Community
  • 1
  • 1
Romz
  • 1,437
  • 7
  • 36
  • 63

3 Answers3

2

It doesn't actually say that. It says "Cannot implicitly convert type 'int' to 'uint'. An explicit conversion exists (are you missing a cast?)"

That's because 1 << x will be of type int.

Try 1u << x.

harold
  • 61,398
  • 6
  • 86
  • 164
1
UInt32 number = 40;
Int32 x = 5;
number &= ~((UInt32)1 << x);
Tarik
  • 10,810
  • 2
  • 26
  • 40
  • Yes, the shifter has to be signed, the shiftee can be unsigned. And `(UInt32)1` can be written `1U` – H H Jul 14 '13 at 12:39
0

You can cast the result, which is a long, back to a uint if you replace the compound operator &= with a normal &:

uint number = /*...*/;
number = (uint)(number & ~(1 << x));

Another way would be to use the unchecked block:

uint number = /*...*/;
unchecked
{
    number &= (uint)~(1 << x);
}
pascalhein
  • 5,700
  • 4
  • 31
  • 44