unreleased unreleased - 1 year ago 82
C++ Question

How to toggle a bit n times without using loop in C/C++?

I would like to toggle a bit n times without loop.

like 1(bit) after toggling 3 times will be 0 and so on.
For toggling a bit 1 time I use bit^=1 .
I actually searching a bit manipulation formula to do so.

Answer Source

If I understand correctly, you want to toggle a bit N times.

Now, Toggling a bin N times equals toggling N%2 times so:

b ^= (N%2);

Modulo 2 is the same as N&1 so you can also write:

b ^= (N&1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download