Shift-Left Operator <<

This page was translated by a robot.

The shift-left operator shifts the bits of an integer to the left by a given number and pads the remaining bits 0. The number to be changed is to the left of the operator, the number of bit positions to be shifted is to the right of the operator.












01001001100101100000001011010010
10010011001011000000010110100100
00110010110000000101101001000000
#include <stdio.h>

void printbinary(int x){
  char str[33]; str[32] = '\0';
  int i = 32;
  while(i){i--; str[i] = (x & 1) + '0'; x>>=1;}
  printf("%s\n", str);
}

int main(){
  int x = 1234567890;
  printbinary(x);
  printbinary(x << 1);
  printbinary(x << 5);
  return 0;
}

Also, in C++, the shift-left operator is often associated with outputting to a stream. See the comments on operator overloading below.

Details

The shift-left operator expects two operands as rvalues ​​and is processed from left to right . The return value is an rvalue , which is always an integer type.

The Shift-Left operator is only allowed for integer values. Under C++, the use of the operator on boolean values ​​is also permitted, but these are intconverted into one before the operator is used.

By shifting the bits to the left, the remaining positions at the right end are also 0filled. This corresponds to a logical bit shift in assembler. The shift-left operator is often abbreviated to SHL.

If the number of bits to be shifted is negative or greater than the length of the integer type used in bits, the result is unspecified. Depending on the compiler, other results may arise. In GCC, for example, the number of bits to be unsignedshifted is taken as a number and calculated modulo the register width in bits, but the compiler issues a warning.

<>are mainly used for low-level programming, such as in systems programming. Since they change individual bits, dealing with these operators is also often referred to as bit fiddling (bit fiddling, also to be understood as bit tinkering, or in good Swiss German: Umegfätterle with Bittli). These two operators are rarely used in everyday programming..

An occasional use of the shift-left operator today is to multiply a number by a power of 2. By shifting with 0, 1, 2, 3, ... bits, the first operand is multiplied with 1, 2, 4, 8, .... In earlier times, this was the preferred way of 2multiplying numbers by a power of because a bitshift could be computed faster by the processor than multiplication. In today's processors, this no longer plays a role.

42
84
168
336
printf("%d\n", 42 << 0);
printf("%d\n", 42 << 1);
printf("%d\n", 42 << 2);
printf("%d\n", 42 << 3);