Files
fit-parser/fitparser/crc.go
Thomas Klaehn 2945d90d24 Initial commit
Signed-off-by: Thomas Klaehn <thomas.klaehn@perinet.io>
2026-02-08 07:30:31 +00:00

44 lines
1.2 KiB
Go

package fitparser
// CRC lookup table for FIT files
var crcTable = [16]uint16{
0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401,
0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400,
}
// CalculateCRC calculates the CRC-16 checksum for FIT files
// This uses the CRC-16-ANSI algorithm with polynomial 0x8005
func CalculateCRC(data []byte) uint16 {
crc := uint16(0)
for _, b := range data {
// Compute CRC for lower nibble (bits 0-3)
tmp := crcTable[crc&0xF]
crc = (crc >> 4) & 0x0FFF
crc = crc ^ tmp ^ crcTable[b&0xF]
// Compute CRC for upper nibble (bits 4-7)
tmp = crcTable[crc&0xF]
crc = (crc >> 4) & 0x0FFF
crc = crc ^ tmp ^ crcTable[(b>>4)&0xF]
}
return crc
}
// UpdateCRC updates an existing CRC with new data
func UpdateCRC(crc uint16, data []byte) uint16 {
for _, b := range data {
// Compute CRC for lower nibble (bits 0-3)
tmp := crcTable[crc&0xF]
crc = (crc >> 4) & 0x0FFF
crc = crc ^ tmp ^ crcTable[b&0xF]
// Compute CRC for upper nibble (bits 4-7)
tmp = crcTable[crc&0xF]
crc = (crc >> 4) & 0x0FFF
crc = crc ^ tmp ^ crcTable[(b>>4)&0xF]
}
return crc
}