Hello today I get a weird output on a simple test skecth that is make me crazy.
Until today I believe on avr microcontroller an int was 2 bytes long and If I use the unsigned operator I just adjust the limits of the variable (-32765 to 35765 in case of signed and 0-65535 on a unsigned)
In this simple test that outputs on serial port the binary value of 2 ints declared on different ways I get a 32 bit on a variable like int var1;
Can someone explain me wait is happen here?
int intVar = 65535;
int unsigned intVar2 = 65535;
int pin = 13;
volatile int state = LOW;
void setup()
{
pinMode(pin, OUTPUT);
Serial.begin(9600);
attachInterrupt(0, blink, RISING);
}
void loop()
{
Serial.print("Value in binary without unsigned = ");
Serial.println(intVar,BIN);
Serial.print("Value in binary with unsigned = ");
Serial.println(intVar2,BIN);
delay(2000);
}
void blink()
{
state = !state;
digitalWrite(pin, state);
}
The output on Serial Console:
Value in binary without unsigned = 11111111111111111111111111111111
Value in binary with unsigned = 1111111111111111
Value in binary without unsigned = 11111111111111111111111111111111
Value in binary with unsigned = 1111111111111111
65535 is too large for a signed int variable (intVar). I think that it would cause intVar to do something weird. The first line of your serial output is 4,294,967,295 in decimal (upper limit of unsigned long), and the second line is fine.
I believe the compiler convert it to an unsigned long automatically perhaps because I assign a value larger than 32765 on the signed var
using this int intVar = 65535;
became unsigned long intVar ???
Another question is why the compiler do it automatically since I even not use any specifier unsigned or signed
This is due to signed extension. If you assign a signed variable with a negative value to another signed variable with a larger size, the value is sign extended by replicating the value of the most significant bit of the smaller variable into the extra bits available in the bigger variable. This is why int -1 and long -1 compare as equal although the bit representations are of course very different.