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

I want to convert

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

in

 byte lineOneB = B01100001; 

How to do this in C ++ / Arduino?

+4
source share
5 answers

I'm not sure about the specific limitations 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; } 

Test this code now on Codepad if that helps.

+6
source

Just shift 0 or 1 to your 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); } 
+5
source
 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 ); } 
+4
source

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

If the result should be B01100001 , then byte 0 is MSB (the 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]; } 

Other answers that I saw, if I read them correctly, put the MSB on byte 7.

EDIT: fixed quotes; I have not read it before.

0
source

All Articles