Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 872
aKiwi Avatar asked Jun 13 '10 07:06

aKiwi


People also ask

What does bitwise XOR return?

The bitwise XOR operator ( ^ ) returns a 1 in each bit position for which the corresponding bits of either but not both operands are 1 s.

How do you convert int to bytes?

An int value can be converted into bytes by using the method int. to_bytes().

What does bitwise and return in C?

The & (bitwise AND) in C or C++ takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. The | (bitwise OR) in C or C++ takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 if any of the two bits is 1.

What operator is used to reset a bit?

Explanation: Bitwise operator | can be used to “set” a particular bit while bitwise operator & can be used to “reset” a particular bit.


1 Answers

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));
...
like image 178
R Samuel Klatchko Avatar answered Oct 16 '22 04:10

R Samuel Klatchko