I'm having an issue with the Serial printer on Arduino Mega with IDE 1.8.13.
I'm trying to print an signed int 16 bit. But instead im getting an 32 bit response from the Serial printer. Can someone help me?
void setup() {
// put your setup code here, to run once:
Serial.begin(19200);
int16_t test = -2;
Serial.println(test,HEX);
}
void loop() {
// put your main code here, to run repeatedly:
}
It is an artifact of how Serial.print() is written.
size_t Print::print(int n, int base)
{
return print((long) n, base);
}
The int16_t gets cast as long so the -2 (0xFFFE) gets sign-extended to -2l (0xFFFFFFFE). If 'base' is 10, negative numbers output a minus-sign and then print the negative of the number so in decimal it comes out as "-2". All other bases print the number as unsigned. The -2 prints as "FFFFFFFE".
If you cast the int16_t to uint16_t the sign extension won't occur and the leading zeroes are suppressed so -2 will come out as "FFFE":
I was doing some Bit manipulation... something like that:
unsigned long Adress = 0x10000;
unsigned long data = 0;
signed int Value = 0xFFFE;
data = Adress | Value;
and i was wondering that the fifth nibble of data got overwritten with 1111. So i printed data to the monitor and got the 32bit variable. On my hardware i could recognize that this nibble was overwritten by Value too. So i think it wasn't the print routine.
I tried to mask it out with data &= 0xFFFFF but the byte's of data just didn't change ?!?! I don't know maybe it was just a simple thing.
I declared Value then as signed long and masked the 16 bit out. That worked.