Logical shift

from Wikipedia, the free encyclopedia
Logical shift operators in various programming languages
language Left Right
ARM - assembler lsl lsr
C ++ (unsigned types only) << >>
C (unsigned types only) << >>
Delphi shl shr
Java << >>
Ocaml lsl lsr
Standard ML << >>
Verilog << >>
VHDL sll srl
JavaScript << >>

Under a logical shift ( engl. Logical shift ) is understood in the computer science a bitwise operator , all bits shifts the operand. The logical as opposed to the arithmetic shift neither receives the sign bit nor does it distinguish between the exponent and the mantissa of a number. Each bit of the operand is simply shifted by a given number of positions and the resulting bit positions are padded, usually with zeros.

A logical shift is often used when the operand is viewed as a sequence of bits rather than a number.

Logical shifts can be a useful and efficient way to perform multiplications or divisions of unsigned integers (whole numbers) to the power of two. Shifting to the left by n bits for an unsigned or signed binary number has the effect of multiplying by 2 n . Shifting to the right by n bits for an unsigned binary number is equivalent to dividing by 2 n (and then rounding down).

Because arithmetic shifts and logical right shifts are different, many programming languages ​​have different operators for them. So the arithmetic shift operator at is Java and JavaScript , for example >>; whereas the logical right shift >>>is. Java alone has only one left shift operator ( <<) because arithmetic and logical shifting have the same effect.

The language C again only knows one right shift operator >>. Many C compilers decide the type of right shift based on which integer data type should be shifted; Signed integers are often shifted arithmetically and unsigned integers are shifted logically.

example

example
Rotate right logically.svg
Logical shift to the right by 1 bit
Rotate left logically.svg
Logical shift to the left by 1 bit


The following bit sequence should be shifted logically by 1 bit: 0001 0111 (see pictures)

  • ... to the left results in: 0010 1110
  • ... to the right results in: 0000 1011