Home > other >  Is there any way to simplify the bitwise operation?
Is there any way to simplify the bitwise operation?

Time:12-06

I am studying about bitwise logical operations.(OR,AND,XOR....etc) And I want to know how to simplify the bitwise operation For example: I want to Set A, Clear B, Toggle C, in the same time. if Input is 0100, and output is 1010

if there is any way to perform this bitwise operation? Thanks.

CodePudding user response:

  • Setting is done using OR or NAND[1][2].
  • Clearing is done using AND[2] or NOR[1].
  • Toggling is done using XOR[3] or XNOR[4].

There is no overlap; these are different operations and thus would have to be done separately.

You can perform the same operation on multiple bits at once, but not different operations on different bits.


  1. Requires a negated input.
  2. Requires a negated mask.
  3. Neither the input nor the mask must be negated, or both must be.
  4. Requires a negated input or a negated mask, but not both.

CodePudding user response:

This sounds like a homework so i'll refrain from using your example or giving code but IMHO the cleanest way is probably to to write SET as OR with a number that has ones in the desired positions, bet way to CLEAR is probably to and with a number that has zeros at the desired positions and for toggle you guessed it xor at the desired position this is because anything OR 1 is always 1, anything and 0 is always 0 and something xor 1 is always the inverse of that thing.

usually the compiler can optimize the operations so it's not a real problem on that front

as for an example let's take an 8 bit number

11110000 and set the first and 5th bits, clear the second and 6th bits and toggle the 3rd and 7th bits.

11110000 | 10001000 = 11111000

11111000 & 10111011 = 10111000

10111000 ^(xor) 00100010 = 10011010

  • Related