0

I know I'm missing something so simple here, but I can't figure it out.

If I do char letter = 'A'; then letter = letter << 8, letter = 0, as one should expect, since we are shifting the bits "off the shelf" to the left.

But, if we do this:

char letter = 'A';

void setup() { Serial.begin(9600);

int twoBytes = letter << 8; Serial.println(twoBytes, BIN);

}

void loop() {}

The result is 100000100000000, but why? << has precedence over =, so it should be bitshifting letter left by 8 first, then assigning that value (which should be 0) to twoBytes.

Juraj
  • 18,264
  • 4
  • 31
  • 49
AJ_Smoothie
  • 504
  • 4
  • 13

1 Answers1

4

This is a funny, non-intuitive rule of the C++ language called “integral promotion”. Simply stated, it says that no computation is ever performed on a type smaller than int: anything smaller gets implicitly promoted to int as soon as it appears in an arithmetic or logic expression.

See Implicit conversions in cppreference.com (warnings: it's hairy).

Edgar Bonet
  • 45,094
  • 4
  • 42
  • 81