Bitshifting - Splitting and Combining

Hi all.

I've been doing some work with bitshifting, as I'm working on a project that requires me to send data between multiple arduinos and I'm sending them via the I2C bus. I have successfully split an Int into 2 bytes, sent them, and combined them on the other side via:

  a = lowByte(x);
  x = x >> 8;
  b = lowByte(x);

and

int byteToInt(byte byte1, byte byte2) {
  int gdayMate = (byte1 & 0xff) |
                 ((byte2 & 0xff) << 8);
  return gdayMate;
}

The only thing I need a little clarification on is the use of the '& 0xff'. I have seen other bitshifting examples around which use different statements where that usually sits, e.g. '0xff00' .

Could anyone shine some light on the purpose of this? I understand you need to shift the bits along and insert the least significant bits, which is acheived by the << 8, but the purpose of the '& 0xff' still eludes me.

Feel free to link any documentation that I've clearly missed :stuck_out_tongue:

Cheers

int bytesToInt(byte byteLow, byte byteHigh) {
  int result = byteLow | (byteHigh<< 8);
  return result;
}

That's the receive side. It's on the send side that you might use a bit mask.

This snippet doesn't tell us enough:

  a = lowByte(x);
  x = x >> 8;
  b = lowByte(x);

lacanau:
Hi all.
...

int byteToInt(byte byte1, byte byte2) {

int gdayMate = (byte1 & 0xff) |
                ((byte2 & 0xff) << 8);
  return gdayMate;
}



... but the purpose of the '& 0xff' still eludes me.

as byte1 and byte2 are bytes the & 0xFF doesn't do anything.
If they were ints the FF would cause the selection of the lower 8 bits.

aarg:
This snippet doesn't tell us enough:

  a = lowByte(x);

x = x >> 8;
  b = lowByte(x);

Sorry, I didn't include the Wire.write commands

robtillaart:
as byte1 and byte2 are bytes the & 0xFF doesn't do anything.
If they were ints the FF would cause the selection of the lower 8 bits.

I see. So I guess there are different combinations depending on which bits you a willing to mask? (if you were working with longs for example). Do you know of any sites that explain how you can change it depending on what you want?

Thanks for the responses guys.

lacanau:
Thanks for the responses guys.

the only head's up i'd offer is that this:

 a = lowByte(x);
  x = x >> 8;
  b = lowByte(x);

permanently mangles x

don't forget about

highByte()

or just

b = x >> 8;

:wink:

chek - Bitwise Operators in C and C++ - Cprogramming.com