Romz
Romz

Reputation: 1457

How to clear a single bit in C#?

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 ?

Upvotes: 0

Views: 4186

Answers (4)

GuusK
GuusK

Reputation: 71

Bit manipulation can be done for multiple types using the generic math interfaces defined since .NET7 (C# 11): https://learn.microsoft.com/en-us/dotnet/standard/generics/math.

Clearing a bit:

public static T ClearBit<T>(this T value, int bitNumber) where T :
    IBinaryNumber<T>,
    IShiftOperators<T, int, T>
{
    T mask = T.One << bitNumber;
    return value & ~mask;
}

And setting a bit:

public static T SetBit<T>(this T value, int bitNumber) where T : 
    IBinaryNumber<T>, 
    IShiftOperators<T, int, T>
{
    T mask = T.One << bitNumber;
    return value | mask;
}

The generic interfaces IBinaryNumber<T> and IShiftOperators<T, int, T> are defined for: byte, int, uint, long, ulong, etc.

Upvotes: 0

pascalhein
pascalhein

Reputation: 5856

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);
}

Upvotes: 0

user555045
user555045

Reputation: 64903

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.

Upvotes: 2

Tarik
Tarik

Reputation: 11209

UInt32 number = 40;
Int32 x = 5;
number &= ~((UInt32)1 << x);

Upvotes: 1

Related Questions