简体   繁体   English

C ++ / Arduino:如何将字符串/字符串数组转换为字节?

[英]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? 我如何在C ++ / Arduino中执行此操作?

I'm not sure about specific restrictions imposed by the Adruino platform, but this should work on any standard compiler. 我不确定Adruino平台施加的具体限制,但这应该适用于任何标准编译器。

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. 如果有帮助, 现在可以在Codepad上测试此代码

Just shift 0 or 1 to its position in binary format. 只需将0或1移到二进制格式的位置即可。 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);
}
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 );
}

If you know that the values of your character array will always be either 1 or 0: 如果您知道字符数组的值将始终为1或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);
    }
}

If the result is supposed to be B01100001 , then byte 0 is the MSB (most significant bit), not byte 7 ... 如果结果应该是B01100001 ,那么字节0是MSB(最高有效位),而不是字节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. 我看到的其他答案,如果我正确读取它们,将MSB放在字节7上。

EDIT: Fixed quotes; 编辑:固定报价; miscopied it before. 以前错过了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM