What is bitshifting?

While lazily searching solutions for my simple unrelated problem, i noticed that almost everyone used these weird "<<" and ">>" operators. I know this is called bitshifting, but what does it do?

might help,

1 Like

Bitshifting refers to moving the bits of a variable left or right to change its value

Try this

byte x = 0b00000001;

void setup()
{
  Serial.begin(115200);
  Serial.println(x, BIN);
  for (int b = 0; b < 7; b++)
  {
    x = x << 1; //left shift 1 bit
    Serial.print(x);
    Serial.print(" ");
    Serial.println(x, BIN);
  }
}

void loop()
{
}

NOTE : When using the BIN format specifier leading zeroes are not printed

1 Like

This may be clearer

byte x = 0b00000001;

void setup()
{
  Serial.begin(115200);
  printBin();
  for (int b = 0; b < 7; b++)
  {
    x = x << 1; //left shift 1 bit
    printBin();
  }
}

void loop()
{
}

void printBin()
{
  Serial.print(x);
  Serial.print("\t");
  for (int b = 7; b > 0; b--)
  {
    Serial.print(bitRead(x, b));
  }
  Serial.println();
}
1 Like
byte x = 0b00010000;

byte y = x << 1;

So y now = 0b00100000

The bits have been shifted left 1 bit.

"<<" shift left. Left most bit is lost, and right most bit becomes 0.
">>" shift right. Right most bit is lost, and left most bit becomes 0.
The number after the operator determines how many places you shift.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.