Search code examples
c#.netbit-manipulationbitwise-operatorsulong

How to reset single bit in ulong?


I have ulong number. I need to be able to quickly set and reset single bit. For example:

15 is 1111. By setting 5th bit I will get 47, so 101111

I figured it out how to set a bit:

ulong a = 15;
a |= 1 << 5; // so, now a=47

But I'm struggling how to reset it back to 0. I was trying:

a &= ~(1 << 5);

It doesn't work, because I can't use & operator on ulong variable.

What's the workaround? I need this operation to be as fast as possible.


Solution

  • I can't use & operator on ulong variable.

    That's because 1 is signed. Making it unsigned with U suffix fixes the problem:

    a &= ~(1U << 5);
    

    Demo.