How to flip bits in one operation with c#?

54 Views Asked by At

I'm storing flags in an integer and I would like to flip specific bits in certain conditions.

Condition 1

if bit 3 is true then
   set bit 3 to false
   set bit 2 to true
end if

Condition 2

if bit 5 is true then
   set bit 5 to false
   set bit 4 to true
end if

All the others bits should remain unchanged.

Condition 1 and condition 2 are independent.

Scenario

int input_01 = 0b_10101010_10_10_1  // condition 1 and condition 2
int input_02 = 0b_10101010_00_10_1  // condition 1
int input_03 = 0b_10101010_10_00_1  // condition 2
int input_04 = 0b_10101010_01_01_1  // nothing

// apply solution on inputs above to get expected below
// it could be 1 or 2 operations max

int expected_01 = 0b_10101010_01_01_1
int expected_02 = 0b_10101010_00_01_1
int expected_03 = 0b_10101010_01_00_1
int expected_04 = 0b_10101010_01_01_1
1

There are 1 best solutions below

0
Charlieface On BEST ANSWER

You can use the following function:

int ShiftOneBit(int value, int bit)
{
    return (value & ~bit) | ((value & bit) >> 1);
}

Then use it like this

x = ShiftOneBit(x, 0b100);
x = ShiftOneBit(x, 0b10000);

dotnetfiddle