75 lines
1.9 KiB
Go
75 lines
1.9 KiB
Go
// 提供CRC8校验和计算功能。
|
||
package crc8
|
||
|
||
import (
|
||
"encoding/hex"
|
||
"fmt"
|
||
"os"
|
||
|
||
"github.com/sigurn/crc8"
|
||
)
|
||
|
||
// 根据提供的校验表名称生成对应的校验表
|
||
func hasherSelect(table string) *crc8.Table {
|
||
switch table {
|
||
case "CRC8":
|
||
return crc8.MakeTable(crc8.CRC8)
|
||
case "CDMA2000":
|
||
return crc8.MakeTable(crc8.CRC8_CDMA2000)
|
||
case "DARC":
|
||
return crc8.MakeTable(crc8.CRC8_DARC)
|
||
case "DVB-S2":
|
||
return crc8.MakeTable(crc8.CRC8_DVB_S2)
|
||
case "EBU":
|
||
return crc8.MakeTable(crc8.CRC8_EBU)
|
||
case "I-CODE":
|
||
return crc8.MakeTable(crc8.CRC8_I_CODE)
|
||
case "ITU":
|
||
return crc8.MakeTable(crc8.CRC8_ITU)
|
||
case "MAXIM":
|
||
return crc8.MakeTable(crc8.CRC8_MAXIM)
|
||
case "ROHC":
|
||
return crc8.MakeTable(crc8.CRC8_ROHC)
|
||
case "WCDMA":
|
||
return crc8.MakeTable(crc8.CRC8_WCDMA)
|
||
default:
|
||
return crc8.MakeTable(crc8.CRC8)
|
||
}
|
||
}
|
||
|
||
// 计算给定字节数组的CRC8校验和,返回字节数组
|
||
func CRC8(data []byte, table ...string) []byte {
|
||
crcTable := append(table, "CRC8")
|
||
return []byte{crc8.Checksum(data, hasherSelect(crcTable[0]))}
|
||
}
|
||
|
||
// 计算给定字节数组的CRC8校验和,返回十六进制字符串
|
||
func CRC8Hex(data []byte, table ...string) string {
|
||
return hex.EncodeToString(CRC8(data, table...))
|
||
}
|
||
|
||
// 计算指定文件的CRC8校验和,返回字节数组
|
||
func SumFile(file string, table ...string) ([]byte, error) {
|
||
f, err := os.Open(file)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("未能打开指定文件,%w", err)
|
||
}
|
||
defer f.Close()
|
||
|
||
crcTable := append(table, "CRC8")
|
||
var buf = make([]byte, 0)
|
||
if _, err := f.Read(buf); err != nil {
|
||
return nil, fmt.Errorf("读取指定文件内容出错,%w", err)
|
||
}
|
||
return []byte{crc8.Checksum(buf, hasherSelect(crcTable[0]))}, nil
|
||
}
|
||
|
||
// 计算指定文件的CRC8校验和,返回十六进制字符串
|
||
func SumFileHex(file string, table ...string) (string, error) {
|
||
crc, err := SumFile(file, table...)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
return hex.EncodeToString(crc), nil
|
||
}
|