Serial Transmission of signed int.

Hi,

When I call this method with the value -13 as a signed integer, it spits out:

0x3F3F from the write statements, and F3FF from the print with hex format statements. Does anyone know why this occurs? I assume it has to do with the right shifting with the sign bit. I am expecting F3FF as this would give me my value of -13. 3F3F is incorrect and I have no idea why it is giving me this value.

I am serializing my data into just data so it can be deserialized on the host PC with a .NET library.

void SendInt(int value)
{
  byte lo = byte(value);
  byte hi = byte(value >> 8);
  
  Serial.write(lo);
  Serial.write(hi);
  
  Serial.print(lo, HEX);
  Serial.print(hi, HEX);  
}

Thank you.

Well, it gives me the creeps when the compiler is left to downcast things from int to byte.

Try this:

void SendInt(int value)
{
  byte lo = (byte)(value & 0x00ff);
  byte hi = (byte)((value & 0xff00) >> 8);

  Serial.write(lo);
  Serial.write(hi);

  Serial.print(lo, HEX);
  Serial.print(hi, HEX);
}

Serial.Write should write the proper byte now.

If the above code doesn't Print the proper data, I would check the print sourcecode to see what is occurring. My guess is that it does print properly now though in both Write and Print.