Newbie: Bytes to ints and back

Hey guys,

I'm sure this is trivial but I'm not very good at this stuff, still learning. With a serial interface, I need to take two bytes (big endian) and convert it into an int. Then I need to do some simple math on it, then convert it back to 2 bytes and push it out the serial port. What's the best way to do this?

Thanks in advance!

Take i as your integer to store the two incoming bytes into. Take the high order byte and shift it to the left 8 places (to get it into the high order byte of i)

Then just add the low order byte:

int i = 0;
i= (int)byte1<<8;
i+=byte2

The reverse is pretty easy too. Set i to the byte you want to send, then use bitwise & to mask the high order bits, right-shift them to the align them to the byte you're about to stuff them into and assign that into the high order byte. For the low order byte just mask out the high order bits.

int i = 24601; // or whatever i you want to send
byte high = (i&0xff00)>>8;
byte low = i&0x00ff;

Check out the extended reference at http://arduino.cc/en/Reference/Extended look for the Bitwise Operators section.

Thank you! Much appreciated.