Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 969
Louisa Bickley Avatar asked Dec 16 '25 12:12

Louisa Bickley


1 Answers

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.

like image 139
Sergey Kalinichenko Avatar answered Dec 19 '25 03:12

Sergey Kalinichenko