开发者

Why arithmetic shift halfs a number only in SOME incidents?

Hey, I'm self-learning about bitwise, and I saw som开发者_运维百科ewhere in the internet that arithmetic shift (>>) by one halfs a number. I wanted to test it:

44 >> 1 returns 22, ok
22 >> 1 returns 11, ok
11 >> 1 returns 5, and not 5.5, why?

Another Example:

255 >> 1 returns 127
127 >> 1 returns 63 and not 63.5, why?

Thanks.


The bit shift operator doesn't actually divide by 2. Instead, it moves the bits of the number to the right by the number of positions given on the right hand side. For example:

00101100 = 44
00010110 = 44 >> 1 = 22

Notice how the bits in the second line are the same as the line above, merely shifted one place to the right. Now look at the second example:

00001011 = 11
00000101 = 11 >> 1 = 5

This is exactly the same operation as before. However, the result of 5 is due to the fact that the last bit is shifted to the right and disappears, creating the result 5. Because of this behavior, the right-shift operator will generally be equivalent to dividing by two and then throwing away any remainder or decimal portion.


11 in binary is 1011

11 >> 1 

means you shift your binary representation to the right by one step.

1011 >> 1 = 101

Then you have 101 in binary which is 1*1 + 0*2 + 1*4 = 5.
If you had done 11 >> 2 you would have as a result 10 in binary i.e. 2 (1*2 + 0*1).

Shifting by 1 to the right transforms sum(A_i*2^i) [i=0..n] in sum(A_(i+1)*2^i) [i=0..n-1] that's why if your number is even (i.e. A_0 = 0) it is divided by two. (sorry for the customised LateX syntax... :))


Binary has no concept of decimal numbers. It's returning the truncated (int) value.

11 = 1011 in binary. Shift to the right and you have 101, which is 5 in decimal.


Bit shifting is the same as division or multiplication by 2^n. In integer arithmetics the result gets rounded towards zero to an integer. In floating-point arithmetics bit shifting is not permitted.

Internally bit shifting, well, shifts bits, and the rounding simply means bits that fall off an edge simply getting removed (not that it would actually calculate the precise value and then round it). The new bits that appear on the opposite edge are always zeroes for the right hand side and for positive values. For negative values, one bits are appended on the left hand side, so that the value stays negative (see how two's complement works) and the arithmetic definition that I used still holds true.


In most statically-typed languages, the return type of the operation is e.g. "int". This precludes a fractional result, much like integer division.

(There are better answers about what's 'under the hood', but you don't need to understand those to grok the basics of the type system.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜