Why is the arithmetic shift of half the number only in SOME incidents?

Hey, I myself learn about bitwise, and I saw somewhere on the Internet that the arithmetic shift (β†’) is half the 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.

+7
c # bit-shift
source share
5 answers

The bit shift operator does not actually divide by 2. Instead, it moves the bits of the number to the right by the number of positions specified on the right side. For example:

 00101100 = 44 00010110 = 44 >> 1 = 22 

Notice how the bits in the second line coincide with the line above, just 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 of 5. Because of this behavior, the operator with the right shift will in general be equivalent to dividing by two and then discarding any remainder or decimal part.

+13
source share

11 in binary state - 1011

 11 >> 1 

means that you are shifting your binary representation to the right one step.

 1011 >> 1 = 101 

Then you have 101 in binary format, which is 1 * 1 + 0 * 2 + 1 * 4 = 5.
If you did 11 >> 2 , you would get the result 10 in binary, i.e. 2 (1 * 2 + 0 * 1).

A shift by 1 to the right converts the sum (A_i * 2 ^ i) [i = 0..n] to the sum (A_ (i + 1) * 2 ^ i) [i = 0..n-1] so if your number even (i.e., A_0 = 0), it is divided into two. (sorry for the configured LateX syntax ... :))

+2
source share

Binary has no concept of decimal numbers. It returns the value of truncated (int).

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

+1
source share

The shift of bits coincides with division or multiplication by 2 ^ n. In integer arithmetic, the result is rounded to zero to an integer. In floating point arithmetic, bit offsets are not allowed.

The internal bit offset, well, shifts the bits, and rounding simply means that a bit that falls from the edge is simply deleted (and not that it actually calculates the exact value, and then rounds it). New bits that appear on the opposite edge are always zero for the right side and for positive values. For negative values, one bit is added on the left side, so that the value remains negative (see How two additions work) and the arithmetic definition that I used remains true.

0
source share

In most statically typed languages, the return type of operation is, for example, "INT". This eliminates the fractional result, very similar to integer division.

(There are better answers about being β€œunder the hood,” but you don't need to understand those who understand the basics of the type system.)

0
source share

All Articles