1
votes

I am not sure how this right shift is equal to 0: I understand how shifting works but why does the author say it equals in binary zero but a different result in decimal? Isn't binary zero the same as decimal zero?

0000

Also how does it even equal binary zero?

unsigned int value = 65372U;

As a binary value in a 2-byte variable, this is:

1111 1111 0101 1100

Suppose you now execute the following statement:

unsigned int result = value >> 2; /* Shift right two bits */

The bits in value will be shifted two places to the right, introducing zeros at the left end, and the resultant value will be stored in result. In binary this will be 0, which is the decimal value 16343.

0011 1111 1101 0111

2
It's a misprint: the binary value is given on the next (bottom) line.Weather Vane
Yeah, the examples it gave are right (I think) but that is most certainly not 0 in decimal or binary. It's probably a mis-print.user10957435

2 Answers

1
votes

Your assumption is correct. Binary 0 is the same as integer 0. The book is a misprint at best and plain wrong at worst. Its examples seem to be okay though.

Also, for the record, binary 0 is what you'd expect:

0000 0000 0000 0000

0011 1111 1101 0111 does not equal 0.

0
votes

Bit shifting in practice involves literally moving the bits N places over, so for a shift of 2:

10101101
||||||
 \\\\\\
  \\\\\\
  vvvvvv
00101011

Mathematically right shifting one bit is equivalent to dividing by two, while left shifting is equivalent to multiplying by two. You'll see this optimization used sometimes because shifting is often far faster than multiplying.

It's like how in decimal terms dividing by any power of ten is easy, you just delete a certain number of digits or move the decimal place.