Bitwise operators and converting an int to 2 bytes and back again

aKiwi picture aKiwi · Jun 13, 2010 · Viewed 10.8k times · Source

My background is php so entering the world of low-level stuff like char is bytes, which are bits, which is binary values, etc is taking some time to get the hang of.

What I am trying to do here is sent some values from an Ardunio board to openFrameWorks (both are c++).

What this script currently does (and works well for one sensor I might add) when asked for the data to be sent is:

int value_01 = analogRead(0);  // which outputs between 0-1024

 unsigned char val1;
 unsigned char val2;

//some Complicated bitshift operation           
    val1 = value_01 &0xFF;
    val2 = (value_01 >> 8) &0xFF;  
    
    //send both bytes
    Serial.print(val1, BYTE);
    Serial.print(val2, BYTE);

Apparently this is the most reliable way of getting the data across. So now that it is send via serial port, the bytes are added to a char string and converted back by:

int num = ( (unsigned char)bytesReadString[1] << 8 | (unsigned char)bytesReadString[0] );

So to recap, im trying to get 4 sensors worth of data (which I am assuming will be 8 of those serialprints?) and to have int num_01 - num_04... at the end of it all.

Im assuming this (as with most things) might be quite easy for someone with experience in these concepts.

Answer

R Samuel Klatchko picture R Samuel Klatchko · Jun 13, 2010

Write a function to abstract sending the data (I've gotten rid of your temporary variables because they don't add much value):

void send16(int value)
{
    //send both bytes
    Serial.print(value & 0xFF, BYTE);
    Serial.print((value >> 8) & 0xFF, BYTE);
}

Now you can easily send any data you want:

send16(analogRead(0));
send16(analogRead(1));
...