Strange Integer Overflow

On a 16 bit Arduino Uno using the IDE version 1.8.1

void setup() {
  Serial.begin(115200);
  byte x = 34;
  int y = 32765;
  x = y;
  Serial.println(x);
  Serial.println(x, BIN);
  Serial.println(y, BIN);
}

Gets you:
253
11111101
111111111111101

As you would expect but

void setup() {
  Serial.begin(115200);
  int x = 34;
  long y = 2147483645L;
  x = y;
  Serial.println(x);
  Serial.println(x, BIN);
  Serial.println(y, BIN);
}

Gets you

-3
11111111111111111111111111111101
1111111111111111111111111111101

Anyone know where the extra bits came from (sizeof(x) is still 2 as you would expect)? The value (DEC) is correct but the binary representation is 32 bit and not 16

Yes that certainly seems strange.

My guess would be that it's an optimizer bug.

Casting a long (32 bit) value into an int (16 bit) value sets the sign bit of the result to bit 15 of the long,
that is the nature of a narrowing cast.

The printing issue is because the methods for printing all punt to the most general cases, long and double,
so the value gets cast from int to long along the way - see Print.cpp in the distribution...

Hi MarkT, I like where you are going with this. A quick check shows that the BIN representation of any negative int is shown as if it were 32 bits - as it has been cast to the equivalent long.

Super answer and another thing learned at this end.

I think the underlying issue is that the Print class has been coded for small code footprint,
due to the target being a small microcontroller - niceties of presentation not a priority.

MikeGWem:
On a 16 bit Arduino Uno

Where did you find one of those?

All of mine are 8 bit.

...R

Sorry, but I think about processors in terms of their word size. Just dates me probably to DEC PDPs in the 1970s.

MikeGWem:
Sorry, but I think about processors in terms of their word size.

Is there such a thing as a "word" in an Atmega 328?

I can't recall any mention of it in the datasheet.

...R