4

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?

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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);
}

Comments

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

for ( int i = 7; i >= 0; i-- ) {
    b |= lineOneC[i] << ( 7 - i );
}

Comments

0

If you know that the values of your character array will always be either 1 or 0:

char line[8] = { '0', '1', '1', '0', '0', '0', '0', '1'};

unsigned char linebyte = 0;
for (int i = 7, j = 0; j < 8; --i, ++j)
{
    if (line[j] == '1')
    {
        linebyte |= (1 << i);
    }
}

Comments

0

If the result is supposed to be B01100001, then byte 0 is the MSB (most significant bit), not byte 7 ...

char line[8] = { 0, 1, 1, 0, 0, 0, 0, 1 };
unsigned char b = 0;
for ( int ii = 0; ii < 8; ii++ )
{
  b <<= 1;
  b |= line[ii];
}

The other answers I've seen, if I read them correctly, put the MSB on byte 7.

EDIT: Fixed quotes; miscopied it before.

2 Comments

Did you actually try the code? That answer doesn't work because you quoted the numbers ('0' is not the same as 0). And the subindex 7 is the 8th item in the list in C and C derived languages, because arrays begin at element zero, not element one.
Thanks for the quotes; for some reason when I copied it from my editor earlier (not copy/paste, but retyping it) I didn't realize that I quoted the values; force of habit from quoting them all the time. As for arrays begin at zero - yes, if you read what I put, I said "byte 0" and "byte 7"; I don't normally reference my array positions 1-based, so "byte 7" is actually the eighth character in the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.