0

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)
}
Stampy
  • 456
  • 7
  • 27

1 Answers1

2

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.

Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79
  • Can you show me an example of the first one please? – Stampy May 18 '20 at 13:46
  • Or do you mean something like this: MyValue &= ~(0xF0 << 4) – Stampy May 18 '20 at 13:54
  • 1
    `MyValue = MyValue & ~0xF0`. Assuming that types would be correct. There's a caveat if `MyValue` is of wider type than `0xF0`, may need to use literal of proper type or cast it. Since your question is language-agnostic, I'm not sure how you do it. – Alex Guteniev May 18 '20 at 13:55
  • If you restate the question from "zero four higher bits" to zero everything except lowest four bits, then `MyValue =MyValue & 0xF` is a way to go, no need `~`, and so it is type safe. – Alex Guteniev May 18 '20 at 13:58
  • And if you want to obtain 0xF from 4, you can shift and subtract one: `(1 << 4) - 1` - it is 0xF – Alex Guteniev May 18 '20 at 14:00