how to separate combine and separate bytes [solved]

Hi Friends,

I'm working on a program where I need to combine 4 local bytes into a long 32 bit expression to be processed with other data.

Assuming i start with the variables below:

byte myvar1 =...
byte myvar2 =...
byte myvar3 =...
byte myvar4 =...

which i need to combine to a long variable...

long myvar1234 = myvar1myvar2myvar3myvar4

Once this is completed I need to combine the variables back into into 4 bytes

byte myvar1a =...
byte myvar2a =...
byte myvar3a =...
byte myvar4a =...

Is there an example on how to accomplish such tasks? Many Thanks and may God be with you all.

Do you mean 4 byte binary word?

Explicit shifting and combining:

long myvar1234 = myvar1a ;
myvar1234 <<= 8 ; myvar1234 |= myvar2a ;
myvar1234 <<= 8 ; myvar1234 |= myvar3a ;
myvar1234 <<= 8 ; myvar1234 |= myvar4a ;

Or using a union:

union 
{
  long l ;
  byte b[4] ;
} temp ;

temp.b[0] = myvar1a ;
temp.b[1] = myvar2a ;
temp.b[2] = myvar3a ;
temp.b[3] = myvar4a ;
long myvar1234 = temp.l ;

The order of the bytes in the long depends on the machine’s endianness with this method.

Another way to do the same thing by casting pointer types:

byte array[4] ;
array [0] = myvar1a ;
array [1] = myvar2a ;
array [2] = myvar3a ;
array [3] = myvar4a ;
long myvar1234 = * ((long *) array) ;

You could use a single variable of union type and extract in either format, rather than
have two sets of variables.

Just edited the thread as I found out a good tutorial on how to achieve this.

That really is not a nice thing to do because it make a nonsense of the thread.

It would have been better to add a new post explaining what you had found and providing a link to it.

Thank you both for your replies. I restored the original question

I found an older thread with some details on how to achieve this here: Long to byte

MarkT, Thank you for your example: I can see the example you posted on shifting is a bit different from the one posted on the thread above. Is there any case where one or the other would be preferred?

Many Thanks

Don't know, but you have to be careful not to just shift a byte left by 16 or 24 without ensuring the result is long (not int) on most Arduinos as the default int size is 16 bits. I've only given the shifting for one direction of conversion.

Shifting is just moving the right bits to the right place - its not rocket science, go experiment.