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.
nnet/protocol/modbus/crc.go

44 lines
716 B
Go

package modbus
import "sync"
var crcTable []uint16
var mu sync.Mutex
// crcModbus 计算modbus的crc
func crcModbus(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
}
}