ag_toolsbox/hash/crc8/crc8.go

90 lines
2.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 提供CRC8校验和计算功能。
package crc8
import (
"encoding/hex"
"fmt"
"os"
"github.com/sigurn/crc8"
)
type CRC8Mode int
const (
ORIGIN CRC8Mode = iota
CDMA2000
DARC
DVB_S2
EBU
I_CODE
ITU
MAXIM
ROHC
WCDMA
)
// 根据提供的校验表名称生成对应的校验表
func hasherSelect(mode CRC8Mode) *crc8.Table {
switch mode {
case ORIGIN:
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, mode ...CRC8Mode) []byte {
crcTable := append(mode, ORIGIN)
return []byte{crc8.Checksum(data, hasherSelect(crcTable[0]))}
}
// 计算给定字节数组的CRC8校验和返回十六进制字符串
func CRC8Hex(data []byte, mode ...CRC8Mode) string {
return hex.EncodeToString(CRC8(data, mode...))
}
// 计算指定文件的CRC8校验和返回字节数组
func SumFile(file string, mode ...CRC8Mode) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, fmt.Errorf("未能打开指定文件,%w", err)
}
defer f.Close()
crcTable := append(mode, ORIGIN)
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, mode ...CRC8Mode) (string, error) {
crc, err := SumFile(file, mode...)
if err != nil {
return "", err
}
return hex.EncodeToString(crc), nil
}