Search code examples
arrayscbit-manipulationbitwise-operators

copy of temp char array from for loop to another array


I have a function that gets a const char * data and goes through every byte of makes some bit manipulation and then adds it to another char array, so basically one byte input data should be 4 bytes and 2 bytes should be 8 bytes and so on, however I'm not getting the correct results, I'm not sure if I'm using the memcpy correctly here, any help would be appreciated

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;
}

This is how I call the function

encryptDataAndSend(TX_TASK_TAG, "@BF");

Solution

  • You have a problem with

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

    As temp may or may not have a null character. So strlen will be incorrect

    Perhaps

    memcpy(encryptedData, temp, 4);
    

    Is the right solution.

    EDIT

    In addition encrypted data needs to move forward in each increment of the loop

    ie.

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

    Also perhaps change

    char encryptedData[len * 4];
    

    to

    char encryptedData[len * 4 + 1];
    

    and then

    encryptedData[len * 4] = 0;
    

    to ensure that the string has a null character in it!