I am struggling with some basic bitwise operations, namely converting a long int to bytes, and back again.
This topic is quite well covered on a lot of places, inlcuding this forum.
Yet, I can't figure out why its not working.
I completly forget about why I need this, just a very basic example and even that won't work as expected. So if you would be so kind to help me point out the error of my ways I would be very thankfull indeed!
void loop () {
long n = 1234567890;
byte buf[4];
buf[0] = (byte) n;
buf[1] = (byte) n >> 8;
buf[2] = (byte) n >> 16;
buf[3] = (byte) n >> 24;
long value = (unsigned long)(buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf[0];
Serial.print("input value: ");
Serial.println(n, BIN);
Serial.print("returned value: ");
Serial.println(value, BIN);
Serial.print("returned INT: ");
Serial.println(value);
delay(1000);
}
This returns an int of 210, which is obviously not the same value as I started with
buf[] contains what I expect though. So What I need at this point is to "concatenate" the 4 bytes in buf[] in such a way that it returns the original long int.
No, not at all correct.
The long cast is on the reassembly, but the disassembly is also changed, which is why I queried your assertion the contents of 'buf' were correct.
Casting a 32 bit value to an eight bit value, and then dividing by 256 isn't going to work.