C:小端

标签 c linux arduino raspberry-pi endianness

我正在尝试在 Raspberry Pi(使用 C 编程)和 Arduino(使用 Arduino IDE)之间发送和接收数据。

根据我在互联网上可以找到的内容,它指出两者都是小端格式。

我在 teuniz.net/RS-232 上使用串行通信 (RS232) 和库“RS-232 for Linux and Windows”在它们之间发送整数

据我所知,如果两者都是小端格式,我不需要对位进行任何移位。然而,在我使用以下代码的情况下,我需要移动 Arduino 读取的位。我不确定为什么当两者都是小端时我需要执行位移(为了获得正确的数据)。事不宜迟....

C 代码:

unsigned char buf[4];
int g = 100;
memcpy(buf, (char*)&g, sizeof(int));

// port 24 for ttyACM0
if(RS232_SendBuf(24, buf, sizeof(int)) == -1)
{
    // error processing here
}

Arduino 代码:

long a[4];
long value = 0;

 void loop(){
   if(Serial.available()>=4){
    for(int i = 0; i < 4 ; i++){
      a[i] = Serial.read();
    }

    // Over here i need to shift the LSB of the byte received to the MSB of the long var until the MSB of byte becomes LSB of long var
    // i do not have the code which is faulty right now as its already past midnight and my group mates are already asleep so I will post again in the morning
    value += a[0];
    value += a[1] << 8;
    value += a[2] << 16;
    value += a[3] << 24;

    Serial.println(value); // now it prints out 100 correctly

    value = 0;
   }

 }

感谢所有帮助!对不起,对 C 和端序还是陌生的!

更新:我想我知道为什么会发生上述情况!请在下方评论让我知道我的假设是对还是错!

我在 C 中发送 170 的 int 值。170 在 HEX 中是 0x000000aa。当我 memcpy(这是小端进入的地方)时,它被存储为 aa 00 00 00(LSB 到 MSB)。因此,当我在 arduino 中获取值时,我肯定需要进行移位,因为整数从 MSB 读取到 LSB(并且因为 arduino 中没有内存复制/读取,所以我不关心这里的任何字节顺序问题)。

但是,由于 Arduino 的处理速度很慢(它还有很多其他的东西要计算!!),我可以让我的 C 代码:

int g = 170;
unsigned char buf[4];
// below line not needed anymore??
//memcpy(buf, (char*)&g, sizeof(long));

if(RS232_SendBuf(24, (char *)&g, sizeof(int)) == -1)
{ ... }

想听更多,以便我了解更多!看来我一开始问这个问题的基础就错了!

最佳答案

我觉得你的代码没问题(我还没有运行它)。

  • 假设您有整数 0xaabbccdd .
  • 在 Pi 上,“buf”将包含 dd , cc , bb , aa .他们将按照该顺序发送。
  • 在 arduino 上,a还将包含 dd , cc , bb , aa .
  • 然后你创建value作为(dd << 0) + (cc << 8) + (bb << 16) + (aa << 24) , 给出 0xaabbccdd .

关于C:小端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35727864/

相关文章:

class - Arduino:用户自定义类型 "does not name a type"

c - 使用 libcurl 检索到的 header 信息来确定文件名

c - 无法 malloc char**

c - Ncurses waddch 不打印光标位置处的字符

c++ - 预期在 '[' token 和 + 之前有不合格的 id

C++/Arduino 将 PROGMEM 中存储的二维数组的指针传递给函数

c - Linux内核有getc、putc、seek等简单的C文件操作函数吗?

c - 为什么此代码返回意外结果? (条件变量)

c++ - C++ 多线程 : detach non-class type error

php 从 linux 终端获取文本并回显