Hello all,
I consider myself a pretty solid programmer but I've hit a brick wall on a simple problem. Don't know if there's something major I'm missing, possibly to do with endianness or memory allocation.
My understanding of C representation of whole numbers is that it's binary with the least significant bit on the right, and the most significant bit on the left. For signed values, the most significant bit being set indicates a negative number, and the remaining bits of the number are set according to twos complement.
I would therefore expect positive bytes, ints and longs to behave pretty much the same, and negative numbers would differ only in the selection of where the most significant bit is.
In particular I would expect the number 324 stored in a 4-byte long value to have exactly the same lower bytes as the number 324 stored in a 2-byte int value - the bytes being 1 and 68. The long value would just have two extra zero bytes on the left.
I ran into an issue when writing code based on this assumption and I've summarised the problem into a minimal sketch below. Can anyone explain to me why when this sketch is run, the long value and the int value aren't being reported as 324. How do I have to marshall the bytes into a long or int in order to get the value 324 reported? I may be failing to understand sprintf also.
What I actually see reported is...
Long, Int, Bytes: 1140916224, 17409, 0 0 1 68
//I would expect having the rightmost bytes {1,68} would
//map to an integer value of 324 (e.g. 256 + 68) for both
//int and long. The long starts at byteArray[0] and the int starts at byteArray[2]
byte byteArray[] = {0,0,1,68};
static char stringBuffer[50];
void setup(){
Serial.begin(9600);
}
void loop(){
delay(1000);
long *longPointer = (long*)byteArray;
int *intPointer = (int*)(byteArray+2);
sprintf (stringBuffer, "Long, Int, Bytes: %ld, %i, %i %i %i %i --- ;) \r\n", *longPointer, *intPointer, byteArray[0], byteArray[1], byteArray[2], byteArray[3]);
Serial.print(stringBuffer);
Serial.println();
}