Problem with integer to byte array conversion

I’d like to convert an integer value to a byte array and vice versa.
I’ve got it working on a C/C++ compiler but on the Arduino the conversion from the byte array to the integer value doesn’t work correctly for values > 32767 (int max).

``````long bytesToInteger(byte b[4]) {
long val = 0;
val = b[0] << 24;
val |= b[1] << 16;
val |= b[2] << 8;
val |= b[3];
return val;
}

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);
}

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

// DOES WORK (convert an integer to a byte array)
byte b[4];
integerToBytes(1056964608, b);
for (int i=0; i<4; ++i) {
Serial.println((int )b[i]);
}

// DOESN'T WORK (convert the byte array back to an integer)
long d = bytesToInteger(b);
Serial.println(d);
}

void loop() {
}
``````

The long data type that I’m using seems to be the same on the Arduino as in the C/C++ compiler.

Arduino:
4 bytes
-2147483648 to 2147483647

C/C++ compiler:
4 bytes
-2147483647 to 2147483647

Any ideas? Thanks!

C/C++ compiler: 4 bytes -2147483647 to 2147483647

Broken compiler. That negative range is incorrect.

You could cast the elements of your byte array to "long" before shifting in "bytesToInteger"

Thank you AWOL.

The working bytes to integer code looks like this:

``````  val = ((long )b[0]) << 24;
val |= ((long )b[1]) << 16;
val |= ((long )b[2]) << 8;
val |= b[3];
``````