You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ntool-biz/nmodbus/util/crc.go

44 lines
712 B
Go

package util
import "sync"
var crcTable []uint16
var mu sync.Mutex
// Checksum 计算modbus的crc
func Checksum(data []byte) (crc uint16) {
if crcTable == nil {
mu.Lock()
if crcTable == nil {
initCrcTable()
}
mu.Unlock()
}
crc = 0xffff
for _, v := range data {
crc = (crc >> 8) ^ crcTable[(crc^uint16(v))&0x00FF]
}
return crc
}
// initCrcTable 初始化crcTable
func initCrcTable() {
crc16IBM := uint16(0xA001)
crcTable = make([]uint16, 256)
for i := uint16(0); i < 256; i++ {
crc := uint16(0)
c := i
for j := uint16(0); j < 8; j++ {
if ((crc ^ c) & 0x0001) > 0 {
crc = (crc >> 1) ^ crc16IBM
} else {
crc = crc >> 1
}
c = c >> 1
}
crcTable[i] = crc
}
}