首页 > 解决方案 > CRC - uint64 到两个字节?

问题描述

我正在使用这个CRC 包来计算消息的 XMODEM CCITT crc 值。crc 值是 uint64s,作者演示了将 CRC 码的十六进制值打印为两个字节使用

// crc1 is a uint64
fmt.Printf("CRC is 0x%04X\n", crc1) // prints "CRC is 0x2C89"

如何将其转换为两个字节而不使其成为字符串并拆分它? %04X如果我正确理解 fmt 文档,则每个字节为 base-16 两个字符。

我只知道几件事:(1),我正在为其编写适配器的硬件需要两个字节作为 CRC 值。(2)、那个CRC包的作者显示uint64可以显示为0xFFFF,也就是两个字节。(3),在线 CRC 计算器将这些值显示为两个字节,例如https://www.lammertbies.nl/comm/info/crc-calculation.html。其余的对我来说是新的......

我刚刚从 CRC 包的自述文件中发布了一个片段。由于 uint64 通常为 8 个字节,我真的不明白如何在不丢失数据的情况下做到这一点。

标签: gotype-conversionbytecrcuint64

解决方案


在线CRC计算和免费库

https://www.lammertbies.nl/comm/info/crc-calculation.html

LibCRC – C 中的开源 CRC 库

https://www.libcrc.org/api-reference/

https://github.com/lammertb/libcrc/blob/master/src/crc16.c

/*
 * uint16_t crc_16( const unsigned char *input_str, size_t num_bytes );
 *
 * The function crc_16() calculates the 16 bits CRC16 in one pass for a byte
 * string of which the beginning has been passed to the function. The number of
 * bytes to check is also a parameter. The number of the bytes in the string is
 * limited by the constant SIZE_MAX.
 */

uint16_t crc_16( const unsigned char *input_str, size_t num_bytes ) {

// code Copyright (c) 1999-2016 Lammert Bies

}  /* crc_16 */

C 类型uint16_t是 Go 类型uint16

uint16 = uint16(uint64)

crc16 = 0xFFBB = uint16(0x000000000000000FFBB)

crc16[0], crc16[1] = byte(uint64>>8), byte(uint64)

crc16[0], crc16[1] = 0xFF, 0xBB = byte(0x000000000000000FFBB>>8), byte(0x000000000000000FFBB)


参考:

CRC-16-CCITT:https ://en.wikipedia.org/wiki/Cyclic_redundancy_check

带有 CRC 的 XModem 协议:http ://web.mit.edu/6.115/www/amulet/xmodem.htm


推荐阅读