如何将字节转换为整数?

3
我有一块Arduino板子,从一个程序中读取三个字节,这些字节对应着执行器需要转动的角度。我需要将这些字节转换成整数,以便将这些整数传递给我的执行器。
例如,我知道从程序中接收到的默认静止状态值是127。我编写了一个C#程序来解释这些字节,并将它们转换成一个单独的整数值。但是,在Arduino环境下使用C语言时,我无法弄清如何完成这一操作。我尝试将每个字节强制转换为char并将其存储在字符串中。然而,这会返回毫无意义的乱码值。
void loop() {
 if(Serial.available() && sw)
 {
  for(int j = 0; j < 3; j++)
  {
    input[j] = Serial.read();
  }
  //command = ((String)input).toInt();
  sw = 0;

}

String myString = String((char *)input);

Serial.println(myString);

}

3个回答

3
  1. The return value of Serial.read() is an int. Therefore, if you have the following code snippet:

    int input[3];
    
    for (int i = 0; i < 3; i++) {
      input[i] = Serial.read();
    }
    

    Then input should store three ints. However, the code:

    char* input[3];
    
    for (int i = 0; i < 3; i++) {
     input[i] = Serial.read();
    }
    

    Will just store the byte conversion from int to char.

  2. If you want to store this as a string, you need to do a proper conversion. In this case, use itoa (see Arduino API description).

    The code snippet would be:

    #include <stdlib>
    char* convertedString = itoa(input[i]);
    

2
以下逻辑将帮助您:
iDst = (cSrc[0] << 16) | (cSrc[1] << 8) | cSrc[2]

否则,您可以在这种情况下使用 union。
union byte2char
{
    char c[4];
    int i;
};

但是联合实现需要考虑小端和大端系统。


我建议使用“int16_t”而不是int - 这取决于程序正在编译的架构,int可以是int8、int16、int32或int64。 - lunatix

2
这应该可以工作:
int command = input[0]*256*256 + input[1]*256 + input[2];

顺便提一下,编写Arduino程序时默认使用的语言是C++而不是C。尽管它们有一些相似之处。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接