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

Posted by aKiwi on Stack Overflow See other posts from Stack Overflow or by aKiwi
Published on 2010-06-13T07:24:16Z Indexed on 2010/06/13 7:32 UTC
Read the original article Hit count: 234

Filed under:
|
|

first time user, Hi guys!

So hopefully someone can help.. My background is php so entering the word of lowend stuff like, char is bytes, which are bits.. which is binary values.. etc is taking some time to get the hang of ;)

What im 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 im 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..

Any help would be greatly appreciated. Thanks

© Stack Overflow or respective owner

Related posts about c++

Related posts about arduino