I like to write functions that can work generically so that is what I would do. I would write one function to test a bit in a byte, one to set a bit, and one to clear a bit.

The general tactic to test a bit is to shift the value 1 to the specified bit position and then check the result of the binary AND operation between the shifted bit and the byte. To set a bit is very similar - shift a one to the right place and OR it with the byte. Clearing a bit is a little different : shift the bit, complement the shifted value, and then AND it with the byte.

You can do what you need to by using these three functions. If a bit is set then clear it and if it is clear then set it. Now do this for every bit in the byte. You might have noticed that I keep referring to bytes. That is because if you can do this for one byte then you can do it for as many bytes as you want. Just tell it how many bytes you passed or pass them to the function one at a time.

14,932,407 members

IF bit == 1

bit = 0

ELSE

bit = 1

REPEAT

Try this:

unsigned int orig = 0x0F1E3C78;

unsigned int flip = 0;

for (int i = 0; i < 32; ++i)

{

if ((orig & (1 << i)) == 0)

flip = flip + (1 << i);

}

But there is a much simpler solution: Using XOR.