Language: EN

como-usar-desplazamiento-binario

What is and how to use the binary shift operation

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 to the 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 bits to the left, each power has one more number. That is, it is like we multiplied the whole number by two.

<< 1101100
Power32168421
Multiply3284

On the contrary, shifting to the right is equivalent to dividing by two.

>> 1001011
Power32168421
Multiply821

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

Left Shift

Left shifting is an operation that moves all the bits of a binary number to the left by a specified 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, 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, it is like multiplying 1011 by 2 two times.

Right Shift

Right shifting is an operation that moves all the bits of a binary number to the right by a specified 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, 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 times (discarding the remainders).