-2

I have a byte and I want to test if Bit 1 is turned on.

The condition I wrote is: if(byte & (1 << 0)) return true;

Confusion: I not understand how to read a byte.

Is Bit 1 this? ie. (1 << 0)

00000000
       ^

Or this? (1 << 1)

00000000
      ^ 

In other words, do we read a byte from 0 -7 or 1 - 8?

Shaz
  • 1,443
  • 1
  • 27
  • 67
  • Possible duplicate of [What are bitwise shift (bit-shift) operators and how do they work?](https://stackoverflow.com/questions/141525/what-are-bitwise-shift-bit-shift-operators-and-how-do-they-work) – Ken White Mar 24 '19 at 05:30
  • Possible duplicate of [How do you set, clear, and toggle a single bit?](https://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit) – klutt Mar 24 '19 at 06:16
  • I asking how to semantically read a byte when bit-shifting – Shaz Mar 24 '19 at 06:32

1 Answers1

0

In computer science, counting always starts from 0. So the 0th bit is the rightmost one. That's why, in the example in that answer, 110 (6) << 1 becomes 1100 (12). This also means that shifting by 0 is a null operation (it doesn't do anything).

This also means that for your case, if you want to test the rightmost bit, all you need to do is byte & 1 - no shifting necessary.

Niayesh Isky
  • 1,100
  • 11
  • 17
  • Thanks for ur answer. Just to clarify my understanding. We count a byte from 0 to - 7. The rightmost bit is called bit 0... and if I want to turn on bit 1 - we're semantically talking about bit 2 (if counted from 1 - 8)? – Shaz Mar 24 '19 at 05:51
  • Yes, you have it correctly, the bits in the byte will be indexed `[7 6 5 4 3 2 1 0]` (e.g. first-bit, index `0`, second-bit index `1`, etc...). – David C. Rankin Mar 24 '19 at 05:57
  • I see. Also trying to understand last example in your answer: say if I had; if (packet & (1 << 3) shouldn't it be true only if bit-4 (aka bit 3 counted from 0) of packet is set to 1? – Shaz Mar 24 '19 at 06:07
  • Yes, that's right. Think about bits as a set of blocks on a table, where you can only see the one that's on the right. Anytime you want to see any other blocks, you have to shift them left or right to focus on a different block. So if you start by focussing on the first bit from the right, you have to shift three times to be able to see the fourth bit from the right. However, to avoid confusion when talking to other developers, I recommend you adopt the starting-at-0 terminology, because it's the most well-established and everyone will understand what you mean. – Niayesh Isky Mar 24 '19 at 16:31