UART shows weird value

Hi!

I'm using Arduino for a while and I just encountered some strange behavior: following code

c = Serial.read();
      Serial.print(c, HEX);Serial.print(" - ");Serial.print(dataLength);Serial.print(" - ");Serial.println(dataInLength);

produces the following output in the terminal: "FFFFFFFF - 16 - 16".

How is it possible that a char returns FFFFFFFF ?

Did I do something wrong in my program?

Thank you in advance for your support!

Julien

Serial.read() returns a 16 bit signed int. It needs to do this so that it can return -1 when there is no data available to read. See Serial.read() - Arduino Reference

Returns

The first byte of incoming serial data available (or -1 if no data is available). Data type: int.

Note that the description of what is returned does not actually make sense because a byte cannot have a value of -1

Thanks UKHeliBob,

You're right regarding the returned value. However, the data displayed in the terminal is a 32bits value (0xFFFFFFFF). And even if this value would be a 16bits signed int, it's casted into a char as c is is declared as char.
I still don't understand this issue...

Thanks!

Julien

what is your input?

All of it, please.

i get "FFFFFFFF" when a char value of -1 is printed
i think the underlying code in Serial.print() is sign extending the value. i don't know what the default type is being used for a hex value

consider
output

FFFFFFFF
 ⸮ -1 0xffff

char s [80];

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

    char c = -1;
    Serial.println ((char) c, HEX);

    sprintf (s, " %c %d 0x%x\n", c, c, c);
    Serial.println (s);
}

void loop ()
{
}

what? it was allways 1 byte of 8 bits

use this

if (Serial.available>0) c = Serial.read();
      Serial.print(c, HEX);Serial.print(" - ");Serial.print(dataLength);Serial.print(" - ");Serial.println(dataInLength);

If it were a byte then how could it return -1, which is what it does if there is nothing to read ?

See Serial.read() - Arduino Reference

so, do you mean it is not uint8_t, but int8_t or int16_t ?

You have the source code - why not look?

it is easier to write sketch and check

void setup() {
  Serial.begin(115200);
  Serial.println(sizeof(Serial.read()));
}

void loop() {}

it say 2, so the "-1" is int16_t
thank you. i did not know this detail.

Well, the page that I linked to does say that it returns an int so the size should not be a surprise. Using an ESP32 the size is, of course, 4

I don't always recommend it, because it's not always completely up-to-date, but there's always the reference