Serial.print issue 16,32bit

Hey,

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:

}

Which is nothing to do with getting the IDE working, which is what the the section you posted in is about.

So I have moved your post here. Please be careful where you post in future.

What were you expecting to see hear? Looks fine for what you have asked the software to do.

In computing minus numbers are normally represented by the two's complement of the positive number.

the compiler appears to have converted the int16_t println() parameter to a 32bit and sign extended it
try masking it to 16 bits

Serial.println(test & 0xFFFF,HEX);

also avoid using images to display Serial Monitor output
copy the text and upload that

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":

Serial.println((uint16_t)test,HEX);

If you want it to come out as "-2"

  if (test < 0)
  {
    Serial.print('-');
    Serial.println(-test, HEX);
  }
  else
    Serial.println(test, HEX);

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.

greetings

when evaluating

data = Adress | Value;

Address is unsigned long so Value is converted to unsigned long with the sign extended to give the result data = 0xFFFFFFFE
try

data = Adress | (Value & 0xFFFF);

which should give 0x1FFFE

on an ESP32 where int is 32 bits

data = Adress | Value;

would give 0x1FFFE

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