0

I'm trying to change the value of x from 5 to 7 to 6 using these bitwise operators. However, the second time where it says x = (x|(0 << 0)); yields no change and is ignored when I trace it.

No errors. Any tips?

int main() {
    unsigned short x = 5;
    
    x = (x|(1 << 1));
    printf("%hd\n", x);
    x = (x|(0 << 0));
    printf("%d\n", x);
  return 0;
}
  • `0 << 0` is 0. `x | 0` is `x`. If you wish to _remove_ bit 0 you can mask it: `x &= ~1U` – paddy Oct 12 '20 at 22:54
  • and what is `0 << 0`? I think you mean `1 << 0` in this case. That won't give you a 6 though as 5 is binary 101. You need to clear the low bit and set the 2nd lowest bit to do that. – Michael Dorgan Oct 12 '20 at 22:54
  • No I don't mean that I want 0 << 0 because I want to replace the 0th bit like index 0 with the value 0. So I want to remove the first 1 in the byte and make it a 0 – Chris Lewis Oct 12 '20 at 22:57
  • @paddy can you elaborate? – Chris Lewis Oct 12 '20 at 22:58
  • Uhh, sure. These are common bitwise operations. `~` is the bitwise-not and `&` is bitwise-and. Write it on paper and do it. You'll see. – paddy Oct 12 '20 at 23:01

0 Answers0