# Bit shifting

I'm trying to read bytes that an i2c device is putting out and i'm not shore how to collect them?

Is the:

``````Wire.write((int)(eeaddress >> 8));   // MSB
Wire.write((int)(eeaddress & 0xFF)); // LSB
``````

of this:

``````byte readTouch(int deviceaddress, unsigned int eeaddress, byte data )
{
byte rdata = 0xFF;

Wire.write((int)(eeaddress >> 8));   // MSB
Wire.write((int)(eeaddress & 0xFF)); // LSB
Wire.write(data);
Wire.endTransmission();

if (Wire.available()) rdata = Wire.read();

return rdata;
}
``````

The same as:

`````` while(Wire.available())    // slave may send less than requested
{
byte a = Wire.read();
byte b = Wire.read();
byte c = Wire.read();
byte d = Wire.read();
byte e = Wire.read();
byte f = Wire.read();
byte g = Wire.read();
byte h = Wire.read();
byte i = Wire.read();
``````

where it basically grabs the bytes one by one? Why do bit shifting in the top?

Because you are trying to get both bytes of an int and send them as bytes.

The Wire.write() function sends an 8-bit value (1 byte), "eeaddress" is 2 bytes. So the first bit shift sends the last 8 bits and the second bit shift sends the first 8 bits. If you tried to use Wire.write(eeaddress) then it would just chop off the last 8 bits.

Wire write() is an overloaded method that allows you to write one byte at a time or several. Your first code example is writing the data a byte at a time, so the bit shifting is done to break the int data into the high eight bits (e.g., MSB) and the low eight bits (e.g., LSB) of the two-byte integer. The other two pieces of code you have shown are reading the data one byte at a time.

An alternative way to do the writes is to use a union comprised of a two element byte array and an int. This would allow you to write the int data without doing the bit shifting explicitly.

Your first code example is writing the data a byte at a time, so the bit shifting is done to break the int data into the high eight bits (e.g., MSB) and the low eight bits (e.g., LSB) of the two-byte integer.

But OP is stupidly casting the resulting byte to an int, so the useful portion is discarded.