| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 | package networkimport (	"bytes")const (	hexTable  = "0123456789abcdefABCDEF"	hexPrefix = "0x")type Byte bytefunc (b Byte) Hex() string {	dst := make([]byte, 2)	dst[0] = hexTable[b>>4]	dst[1] = hexTable[b&0x0f]	return string(dst)}func (b Byte) String() string {	return b.Hex()}type Bytes []byte// TrimNUL 移除 b 字符串内的 NUL 符号// 参考 https://stackoverflow.com/questions/54285346/remove-null-character-from-stringfunc (b Bytes) TrimNUL() Bytes {	return bytes.Replace(b, []byte("\x00"), nil, -1)}// TrimEnter 移除 b 字符串内的回车符号func (b Bytes) TrimEnter() Bytes {	return bytes.Replace(b, []byte("\r"), nil, -1)}// Remake 将 b 重新分配并返回新的变量func (b Bytes) Remake() Bytes {	if len(b) == 0 {		return []byte{}	}	n := make([]byte, len(b))	for i := 0; i < len(b); i++ {		n[i] = b[i]	}	return n}// Equal 与 dst 进行比较func (b Bytes) Equal(dst Bytes) bool {	if len(b) != len(dst) {		return false	}	return bytes.Equal(b.Remake(), dst.Remake())}// CRC16 使用 Bytes 创建用于 Modbus/TCP 协议 2 个字节的 CRC 校验码(CRC16)// 具体应用时需要使用 BigEndian (大端模式) 或 LittleEndian 转换func (b Bytes) CRC16() uint16 {	var crc uint16 = 0xFFFF	for _, n := range b {		crc ^= uint16(n)		for i := 0; i < 8; i++ {			if crc&1 != 0 {				crc >>= 1				crc ^= 0xA001			} else {				crc >>= 1			}		}	}	return crc}// Hex 输出包含空格的 hexfunc (b Bytes) Hex() string {	if len(b) <= 0 {		return ""	}	dst := make([]byte, len(b)*2)	for i, v := range b {		dst[i*3] = hexTable[v>>4]		dst[i*3+1] = hexTable[v&0x0f]	}	dst = dst[:len(dst)-1]	return string(dst)}// HexTo 返回不包含空格的 hexfunc (b Bytes) HexTo() string {	if len(b) <= 0 {		return ""	}	dst := make([]byte, len(b)*3)	for i, v := range b {		dst[i*3] = hexTable[v>>4]		dst[i*3+1] = hexTable[v&0x0f]		dst[i*3+2] = 32 // 补充空格	}	dst = dst[:len(dst)-1]	return string(dst)}func (b Bytes) String() string {	return b.HexTo()}
 |