como-usar-desplazamiento-binario

What is and how to use the binary shift operation

  • 3 min

The left shift << and right shift >> operations are fundamental 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 represents a factor that multiplies a power of 2.

For example,

Binary010110
Power32168421
Multiply by1642

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

<< 1101100
Power32168421
Multiply by3284

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

>> 1001011
Power32168421
Multiply by821

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

Left Shift

The left shift is an operation that moves all 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 positions shifted.

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)
Copied!

The result is 101100, which equals 44 in decimal. That is, it’s like having multiplied 1011 by 2 twice.

Right Shift

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

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

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)
Copied!

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