gpt4 book ai didi

c# - 相当于 Windows 中的 Unix cksum

转载 作者:行者123 更新时间:2023-11-30 20:08:50 26 4
gpt4 key购买 nike

我下载了一个文件及其校验和(由 cksum Unix 命令生成)。

所以,我想在我的 C# 应用程序中测试校验和是否适合我下载的应用程序。

我查看了 chsum 的 Unix 手册页:

  The cksum command calculates and prints to standard output a checksum
for each named file, the number of octets in the file and the
filename.

cksum uses a portable algorithm based on a 32-bit Cyclic Redundancy
Check. This algorithm finds a broader spectrum of errors than the
16-bit algorithms used by sum (see sum(1)). The CRC is the sum of the
following expressions, where x is each byte of the file.

x^32 + x^26 + x^23 +x^22 + x^16 + x^12 + x^11 + x^10 + x^8 + x^7
+ x^5 + x^4 + x^2 + x^1 + x^0

The results of the calculation are truncated to a 32-bit value. The
number of bytes in the file is also printed.

所以我写了一个简单的程序来求和:

byte[] arr = File.ReadAllBytes(@"MyApp").ToArray();

int cksum = 0;

foreach (byte x in arr)
{
cksum += (x ^ 32 + x ^ 26 + x ^ 23 + x ^ 22 + x ^ 16 + x ^ 12 + x ^ 11 + x ^ 10 + x ^ 8 + x ^ 7 + x ^ 5 + x ^ 4 + x ^ 2 + x ^ 1 + x ^ 0);
}

但是校验和不一样,我该如何解决这个问题?

谢谢


编辑

1)修改后的算法为:

uint cksum = 0;

foreach (byte b in arr)
{
var x = (uint)b;

cksum += (IntPow(x, 32)
+ IntPow(x, 26) + IntPow(x, 23) + IntPow(x, 22)
+ IntPow(x, 16) + IntPow(x, 12) + IntPow(x, 11) + IntPow(x, 10)
+ IntPow(x, 8) + IntPow(x, 7) + IntPow(x, 5) + IntPow(x, 4) + IntPow(x, 2) + IntPow(x, 1) + IntPow(x, 0));
}

2) 我使用了 class Crc32 : HashAlgorithm

给定 Crc32 为 2774111254 的 Unix 文件

  • 1) 给我:4243613712
  • 2) 给我:3143134679(种子为 0)

我做错了什么!?

最佳答案

在 C# 中,^ 符号是异或运算符。你想要函数 Math.Pow .

这给出了两个 float 的乘数,在 How do you do *integer* exponentiation in C#? 中建议了替代方案

因此,您的代码将类似于:

cksum += Math.pow(x,32) + Math.pow(x,26)

还要注意最后一条语句:

The results of the calculation are truncated to a 32-bit value. The number of bytes in the file is also printed.

这是有符号的(int)还是无符号的(uint)

您当然可以使用以下内容: http://www.codeproject.com/Articles/35134/How-to-calculate-CRC-in-C

关于c# - 相当于 Windows 中的 Unix cksum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6661398/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com