将临时字符数组从 for 循环复制到另一个数组

copy of temp char array from for loop to another array

我有一个函数,它获取一个 const char * 数据并遍历每个字节进行一些位操作,然后将其添加到另一个 char 数组,所以基本上一个字节输入数据应该是 4 个字节,2 个字节应该是8 字节等等,但是我没有得到正确的结果,我不确定我在这里是否正确使用了 memcpy,任何帮助将不胜感激

int encryptDataAndSend(const char *logName, const char *data)
{
  const int len = strlen(data);
  printf("data length: %d \n", strlen(data));
  char encryptedData[len * 4];
  for (uint8_t i = 0; i < len; i++)
  {
    uint8_t v1 = 255;
    uint8_t v2 = 255;
    uint8_t v3 = 255;
    uint8_t v4 = 255;

    char temp[4] = {0};

    printf("char is %d \n", data[i]);

    v1 |= ((data[i] & (1 << 0)) << 2);
    v1 |= ((data[i] & (1 << 1)) << 5);
    v2 |= ((data[i] & (1 << 2)) << 2);
    v2 |= ((data[i] & (1 << 3)) << 5);
    v3 |= ((data[i] & (1 << 4)) << 2);
    v3 |= ((data[i] & (1 << 5)) << 5);
    v4 |= ((data[i] & (1 << 6)) << 2);
    v4 |= ((data[i] & (1 << 7)) << 5);
    temp[0] = v1;
    temp[1] = v2;
    temp[2] = v3;
    temp[3] = v4;
    printf("temp: %s \n", temp);
    memcpy(encryptedData, temp, strlen(temp));
  }
  printf("temp var: %s", encryptedData);
  const int txBytes = uart_write_bytes(UART_NUM_2, encryptedData, strlen(encryptedData));
  ESP_LOGI(logName, "Wrote %d bytes", txBytes);
  ESP_LOG_BUFFER_HEX("SENDDATA_TAG", encryptedData, txBytes);
  return txBytes;
}

这就是我调用函数的方式

encryptDataAndSend(TX_TASK_TAG, "@BF");

你有问题

memcpy(encryptedData, temp, strlen(temp));

As temp 可能有也可能没有空字符。所以 strlen 将是不正确的

也许

memcpy(encryptedData, temp, 4);

是正确的解决方案。

编辑

此外,加密数据需要在循环的每个增量中向前移动

memcpy(encryptedData + 4 * i, temp, 4);

也许还会改变

char encryptedData[len * 4];

char encryptedData[len * 4 + 1];

然后

encryptedData[len * 4] = 0;

确保字符串中有空字符!