Java vs C# BigInteger 产生不同的值

  • 本文关键字:vs BigInteger Java java c#
  • 更新时间 :
  • 英文 :


我在C#中生成与Java相同的BigInteger值时遇到了一些麻烦。 在这两种语言中,我都从字节数组中创建 BigInteger,这些字节以相同的顺序保存相同的值。

Java BigInteger 是这样创建的:

BigInteger hashnum = new BigInteger(1, md.digest());

并产生: 79054595997078811232777738014361687045908459940911070866043475968067897954324

md.digest(( 在两种语言中返回以下值: {-73

, 97, 1, -64, 23, 38, 69, 95, 107, 122, 119, -122, -99, -92, 47, 8, -118, 70, 119, 98, 64, -1, -70, 36}我的 C# 代码:

在末尾添加 0 字节,但不反转字节数组

sbyte[] hashSBytes = md.digest();
if ((hashSBytes[hashSBytes.Length - 1] & 0x80) != 0)
{
Array.Resize<sbyte>(ref hashSBytes, hashSBytes.Length + 1);
}
BigInteger hashnum = new BigInteger((byte[])(object)hashSBytes);

BigInteger 的值为 92590942655695057524171612499701658178022831645290183610636811349839086444983

添加 0 字节并反转字节数组

sbyte[] hashSBytes = md.digest();
Array.Reverse(hashSBytes);
if ((hashSBytes[hashSBytes.Length - 1] & 0x80) != 0)
{
Array.Resize<sbyte>(ref hashSBytes, hashSBytes.Length + 1);
}
BigInteger hashnum = new BigInteger((byte[])(object)hashSBytes);

BigInteger 的值为 82944647536515285715130977031103916663496217450446852247301410452203227690188

在你继续在SitePoint上抨击"SO point纳粹"之前,我认为你在其他地方做错了什么。当您将大整数作为字符串并在 JAVA 和 C# 中解析它时,当您投影到字节数组时,您会得到完全相同的结果。

00,AE,C7,50,D1,1F,EE,E9,F1,62,71,92,2F,BA,F5,A9,BE,14,2F,62,01,9E,F8,D7,20,F8,58,94,00,70,88,90,14

你是对的,在 C# 中相反,但仍然是一样的。

C#

var bi = BigInteger.Parse("79054595997078811232777738014361687045908459940911070866043475968067897954324");
Console.WriteLine(
String.Join(",", 
bi.ToByteArray().Reverse().Select(s=>s.ToString("X2"))));

.JAVA

import java.math.BigInteger;
public class BigIntSample {
public static void main(String[] args) {
// TODO Auto-generated method stub
BigInteger bi = new BigInteger("79054595997078811232777738014361687045908459940911070866043475968067897954324");
byte[] bytes = bi.toByteArray();
System.out.println(byteArrayToHex(bytes));
}
public static String byteArrayToHex(byte[] a) {
StringBuilder sb = new StringBuilder(a.length * 2);
for (byte b : a)
sb.append(String.format("%02X", b).concat(","));
return sb.toString();
}
}

我相信主要问题是在 C# 中,您正在处理sbytes,有符号字节,它们与bytes 的含义完全不同。我可能是错的,但绝对不是"点纳粹"。

和平

我的 C# 代码一直工作正常。我试图匹配的 java 结果是错误的。md.digest(( 在 Java 代码中被调用了 2 次,但它是非静态的,并且在两者之间没有被重置。第一次调用甚至不应该在那里,它只是为了调试,以便我可以将其分配给属性并在调试器中查看值,因为 BigInteger 构造函数直接使用 md.digest((。 在我的调试行调用该方法后,我未能重置这个非静态类中的数组,所以即使我在这一行的调试器中看到相同的值,当它实际创建 BigInteger 并调用 md.digest(( 第二次它收到不同的值时。

最新更新