haiga
July 25, 2023, 9:39am
1
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.
haiga:
sprintf(hex, "%x", crc);
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
b707
July 25, 2023, 9:57am
3
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
b707
July 25, 2023, 10:03am
5
OP takes a uint16_t CRC value, convert it to string with sprintf and only after that he added a "1e" at the front:
gcjr
July 25, 2023, 10:40am
6
can you post the data resulting in the posted value
1 Like
gcjr
July 25, 2023, 11:04am
7
ignore previous
why preprend "0x1e"?
why not
char hex [20];
sprintf (hex, "1E%04X", crc);
Serial.println (hex);
1 Like
system
Closed
January 21, 2024, 11:05am
8
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.