3

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.

Louisa Bickley
  • 297
  • 5
  • 17
  • Possible duplicate of [Bitwise operation on longs](http://stackoverflow.com/questions/9924762/bitwise-operation-on-longs) – itsme86 May 01 '17 at 18:42
  • 1
    @itsme86 Although the question that you linked explains what's going on, and would definitely put OP on the right track, it does not provide the work-around that OP is looking for, so I am not sure if it's a good candidate for closing as a duplicate. – Sergey Kalinichenko May 01 '17 at 18:46
  • @dasblinkenlight, I guess it too much to expect the OP to realize that the IDE Error Window message `Operator '&=' cannot be applied to operands of type 'ulong' and 'int'` is nearly identical to the [answer proposed](http://stackoverflow.com/a/9925060/2592875) by @ RoyDictus in the proposed duplicate. – TnTinMn May 01 '17 at 20:17

1 Answers1

4

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523