Hi,
I've been trying to send a long integer from an Arduino to my C++ program via the serial port. There seems to be many examples of this when i search, but I've not had much luck except for one example. This example seems to work, but not when I send a negative integer. I'm not sure if it is my arduino code or my c++ code, or both that needs changing. Does anyone know how I could adjust this to work with negative numbers too?
// Ardunino Code - Sends 4 bytes to C++ program on PC
void IntegerToBytes(long val, byte b[4]) {
b[0] = (byte )((val >> 24) & 0xff);
b[1] = (byte )((val >> 16) & 0xff);
b[2] = (byte )((val >> 8) & 0xff);
b[3] = (byte )(val & 0xff);
}
long n = 23580;
byte b[4];
IntegerToBytes(n, b);
for (int i=0; i<4; ++i) {
Serial.write((int )b[i]);
}
-
// C++ code to convert the captured bytes back into a long integer
long int int32 = bytesIn[3] | ( (int)bytesIn[2] << 8 ) | ( (int)bytesIn[1] << 16 ) | ( (int)bytesIn[0] << 24 );
If I send 23580, int32 becomes 23580
If I send -23580, int32 becomes -28