Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ / Arduino: How do I convert a string/char-array to byte?

I want to convert

char lineOneC[8] = {0,1,1,0,0,0,0,1}; 

into

byte lineOneB = B01100001;

How do I do this in C++ / Arduino?

like image 1000
JNK Avatar asked Dec 07 '22 00:12

JNK


2 Answers

I'm not sure about specific restrictions imposed by the Adruino platform, but this should work on any standard compiler.

char GetBitArrayAsByte(const char inputArray[8])
{
    char result = 0;
    for (int idx = 0; idx < 8; ++idx)
    {
        result |= (inputArray[7-idx] << idx);
    }
    return result;
}

A test of this code is now on Codepad, if that helps.

like image 51
Billy ONeal Avatar answered Dec 24 '22 08:12

Billy ONeal


Just shift 0 or 1 to its position in binary format. Like this

char lineOneC[8] = {0,1,1,0,0,0,0,1}; 
char lineOneB = 0;
for(int i=0; i<8;i++)
{
    lineOneB |= lineOneC[i] << (7-i);
}
like image 34
DReJ Avatar answered Dec 24 '22 07:12

DReJ