Arduino removes meaningless zeros by itself

String GF_Common_Crc16(uint8_t *data, uint16_t length)
{
      uint16_t crc = 0xFFFF;
      uint16_t poly = 0x8408;
      uint8_t cur_byte = 0x00;
      for(uint16_t i=0; i < length; i++){
      cur_byte = data[i];
      for(uint8_t j=0; j < 8; j++){
      if ((crc & 0x0001) ^ (cur_byte & 0x0001))
      {
        crc = (crc >> 1) ^ poly;
      }
      else
      {
        crc >>= 1;
      }
      cur_byte >>= 1;
      }
      }
      crc = ~crc;
      crc = (crc << 8) | ((crc >> 8) & 0xFF);
      char hex[6];

      sprintf(hex, "%x", crc);
      puts(hex);
      String crc1;
      crc1 = "1e" + String(hex);
      crc1.toUpperCase();
      return crc1;
}

I want to calculate the crc but it lost the number 0
For example: 1E0202 then it returns 1E202
How to fix it? Thank you to much.

Use sprintf(hex, "%06x", crc);. The zero indicates to print leading zeroes, the 6 indicate a minimum width of 6 characters.

You have however a worse problem; 6 characters don't fit in a 6-byte c-string; you need to keep space for a nul-terminator so hex should have a size of 7.

3 Likes

At the moment of calling sprintf OP has 4 chars only, so the a 6-byte c-string is enough.
For the same reason the correct format for sprintf would be

1 Like

Based on below, it should be six :wink:

OP takes a uint16_t CRC value, convert it to string with sprintf and only after that he added a "1e" at the front:

can you post the data resulting in the posted value

1 Like

ignore previous

why preprend "0x1e"?

why not

    char hex [20];
    sprintf (hex, "1E%04X", crc);
    Serial.println (hex);
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.