换档时的奇怪行为

Weird behavior when shifting

当我使用 Cypress 的 SDCard 库写入 SD 卡时,我遇到了一些挑战。因为我必须加快一切,所以使用 sprintf() 和类似的是不可能的。

库只允许我以 uchars 或字符串写入 SD 卡。不幸的是我的值都是 int16_t。所以这里出现了问题:

int16_t  ax = -15000;
         ay = -10000; 
         az = -32760;
         gx = 32760;     
         gy = 25000; 
         gz = 10;    
         mx = -10;
         my = 20;
         mz = 0;

// Then I put it into an array

char suma[] = {
    ((uint16_t) ax) & 0xff,
    ((uint16_t) ax) >> 8,
    ((uint16_t) ay) & 0xff,
    ((uint16_t) ay) >> 8,
    ((uint16_t) az) & 0xff,
    ((uint16_t) az) >> 8,

    ((uint16_t) gx) & 0xff,
    ((uint16_t) gx) >> 8,
    ((uint16_t) gy) & 0xff,
    ((uint16_t) gy) >> 8,
    ((uint16_t) gz) & 0xff,
    ((uint16_t) gz) >> 8,

    ((uint16_t) mx) & 0xff,
    ((uint16_t) mx) >> 8,
    ((uint16_t) my) & 0xff,
    ((uint16_t) my) >> 8,
    ((uint16_t) mz) & 0xff,
    ((uint16_t) mz) >> 8,
    0
};

当我检索数据时出了点问题。在 gz 之前数据都很好。它显示 10 好,但其余的都不见了。

将 10 更改为 257 可以消除问题,-10 也可以,这意味着当我向右移动一个较低的非负值时会发生错误。

怎么了?我希望你有一些见解:)

在将 int16_t 转换为 uint16,然后再转换为 char 时,您可能最终会向库发送 null char (\0)。

库 - 只接受 char[]string - 可能将前者转换为 c 字符串,以 null char 结尾。这意味着您的最高有效字节 (0x00) 正在提前终止字符串。任何低于 257 的 uint16 都会在最重要的位置产生空字符。

例如:

0000 0000 = [0, 0] = [0x00, 0x00]   // 2 null chars, only the first will get across
0001 0000 = [1, 0] = [0x01, 0x00]   // null char
                                    // ...
1111 0000 = [256, 0] = [0xff, 0x00] // null char
1111 0001 = [256, 1] = [0xff, 0x01] // not null char

尝试将您的 char[] 显式转换为 std::string 并指定其大小。例如:

std::string s("ab[=11=]c", 4);