Search code examples
bit-manipulationbit-shift

Shift loop value to first four bit


I have a question for a not specific programming language. I can use Shifting and Bitwise Operators

MyValue is for example 0xF5 (1111.0101). Now I want to count up the first four bits like from 0 up to 15 (each bit combination).

  • 0001.0101
  • 0010.0101
  • 0011.0101
  • 0100.0101

Is this correct?

for-Loop (counting up to 15, loop variable is LoopVariable)
{
   // Set first four bits to 0 e.g 1111.0101 to 0000.0101
   MyValue = MyValue | (0 << 4)

   // Set first four bits according to current loop e.g. 0000.0101 to 0001.0101
   MyValue = MyValue | (LoopVariable  << 4)
}

Solution

  • The second operation is correct

       MyValue = MyValue | (LoopVariable  << 4)
    

    it sets high bits to bits of LoopVariable.

    The first is not:

       MyValue = MyValue | (0 << 4)
    

    It does not clear any bits, it is no-operation. To clear bits use bit-wise and instead of or, and apply inverted mask with bit-wise not.