Language: EN

como-usar-desplazamiento-binario

What is and how to use the binary shift operation

The left << and right >> shift operations are basic operations in binary data manipulation.

These operations simply shift the bits of a number one or more positions to the left or right.

Why are these two operations useful? If we remember, each digit of a binary number expresses a factor that will multiply a power of number 2.

For example,

Binary010110
Power32168421
Multiply1642

If we shift all the bits to the left, each power has one more number. That is, it is as if we had multiplied the entire number by two.

<< 1101100
Power32168421
Multiply3284

Conversely, shifting to the right is equivalent to dividing by two.

>> 1001011
Power32168421
Multiply821

These operations have the advantage that they are very fast and efficient at the hardware level. Therefore, they are widely used internally by the computer.

Left shift

The left shift is an operation that moves all the bits of a binary number to the left by a certain number of positions.

This shift is equivalent to multiplying the binary number by powers of two, depending on the number of shifted positions.

For example, when shifting the binary number 1011 (11 in decimal) two positions to the left:

    1011 (original binary)
<<  2   (left shift of two positions)
_________
  101100  (result)

The result is 101100, which is equal to 44 in decimal. That is, as if we had multiplied 1011 by 2 two times.

Right shift

The right shift is an operation that moves all the bits of a binary number to the right by a certain number of positions.

This shift is equivalent to performing an integer division by powers of two, depending on the number of shifted positions.

For example, when shifting the binary number 1011 (11 in decimal) two positions to the right:

    1011 (original binary)
>>  2   (right shift of two positions)
_________
  10  (result)

The result is 10, which is equal to 2 in decimal, which is the same as if we had divided 11 by 2 twice (discarding the remainders).