Bitwise operations, please help me not go mental!

Dear All,

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.

Any help would be very much appreciated!

Try adding an L to the end of your long constant.

Makes no difference in above example.

You may want to look at how you are taking 'n' apart.
Your operators are fine, but precedence is a problem.

(sorry, posted from my phone before - couldn't see all the code)

buf[] contains what I expect though

Really?

Precedence errors in disassembly and cast error in reassembly of the 32 bit value. Corrected sketch:

void setup() {
  Serial.begin(9600);
  
  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 | 
               ((unsigned long)buf[2]) << 16 |
               ((unsigned long)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);

  exit(0);
}

void loop () {
}

Ok, that works.

But looking at the above version and my version, the only difference seems to be the cast to an unsigned long on each byte, correct?

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.