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

Recommended Answers

All 4 Replies

instead of all that shifting I just store it in a char array then xmit the array

inx x = -123;
unsigned char buf[sizeof(int)];
memcpy(buf,&x,sizeof(int);
// now just xmit buf
 Serial.write(buf,sizeof(buf));


 // C++ code to convert the captured bytes back into a long integer
 int x;
 memcpy(&x,buf,sizeof(int));

 // or this works too
 x = *(int *)buf;

Not considered in the above code is endianess
Binary data is not directly transferrable between MS-Windows and *nix because the byte order is different.

instead of all that shifting I just store it in a char array then xmit the array

This introduces a portability issue that doesn't exist with shifting (ie. byte order), though whether that matters to the OP hasn't been established.

There are ways to handle that too.

Thanks guys. That sorted it. I tried keeping the bit shifting method on the C++ part (so it would be more portable, allthough it doesn't really matter for my application), but it seemed to half work. I tried the memcpy though and that seems to work just fine.

// Arduino Code
long int x = -123;
unsigned char buf[sizeof(long int)];
memcpy(buf,&x,sizeof(long int));
Serial.write(buf,sizeof(buf));


// C++ Code
memcpy(&intVal,buf,sizeof(long int)); //This works fine

intVal = buf[0] | ( (int)buf[1] << 8 ) | ( (int)buf[2] << 16 ) | ( (int)buf[3] << 24 );
// This gives the following results...
// send -123 intVal = -123
// send 3687 intVal = 3687
// send -68732 intVal = -124  <---- ?
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.