简体   繁体   English

使用输入字符串在 c# 中生成 CRC32 校验和

[英]Generating CRC32 checksum in c# with input string

I'm trying to generate a CRC32 checksum for the Kraken exchange's orderbooks as described here .我正在尝试按照此处所述为 Kraken 交易所的订单生成 CRC32 校验和。 I found another post in SO that referenced this Github file in order to generate the CRC32 checksum.我在 SO 中找到了另一篇引用此 Github 文件的帖子,以生成 CRC32 校验和。 The issue I have is that I need to generate the checksum based off an input string , where all of the checksum functions I've found take a byte[] as an input.我遇到的问题是我需要根据输入string生成校验和,其中我发现的所有校验和函数都以byte[]作为输入。

I tried converting the string to a byte[] , but it doesn't give me the expected result that I should be getting as per the Kraken docs.我尝试将string转换为byte[] ,但它没有给我按照 Kraken 文档应该得到的预期结果。

string inputString = "50055005010500501550050205005025500503050050355005040500504550050505005000500499550049905004980500497550049705004965500496050049555004950500";
        
Crc32 crc32 = new Crc32();
var byteArr = crc32.ComputeHash(Encoding.ASCII.GetBytes(inputString));
    
Console.WriteLine(Encoding.ASCII.GetString(byteArr));

The value this logs will be ":??"此日志的值将是":??" , where as I'm supposed to be getting "974947235" . ,因为我应该得到"974947235"

Clearly, I must be doing something completely wrong here.显然,我在这里一定做错了什么。 What am I missing?我错过了什么?

ComputeHash returns byte[] , so you will get four bytes back. ComputeHash返回byte[] ,因此您将获得四个字节。 Your 974947235 becomes in hex 3a, 1c, 83, a3 .您的974947235变为十六进制3a, 1c, 83, a3 Or 58, 28, 131, 163 in decimal.或者58, 28, 131, 163十进制。 Trying to print random bytes as characters can only lead to angst and frustration.尝试将随机字节打印为字符只会导致焦虑和沮丧。 Print them as numbers.将它们打印为数字。 Note that 58 is the colon (":") character, so in fact your first character is correct.请注意,58 是冒号 (":") 字符,因此实际上您的第一个字符是正确的。

By the way, there are many CRC-32's, but you seem to have stumbled on to the correct one, as the string you provided does indeed result in the CRC-32/ISO-HDLC : 974947235 .顺便说一下,有很多 CRC-32,但您似乎偶然发现了正确的一个,因为您提供的字符串确实导致CRC-32/ISO-HDLC : 974947235

Mark's post got me half way there.马克的帖子让我成功了一半。 The solution I found was to convert to a hex, and then convert that hex into an int , like so:我找到的解决方案是转换为十六进制,然后将该十六进制转换为int ,如下所示:

Crc32 crc32 = new Crc32();
byte[] byteArr = crc32.ComputeHash(Encoding.ASCII.GetBytes(s));

string hex = BitConverter.ToString(byteArr);

int desiredInt = int.Parse(
   hex.Replace("-", string.Empty),
   System.Globalization.NumberStyles.HexNumber);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM