为什么 C# 和 Java BigInteger 以不同方式转换 byte[]?

Why do C# and Java BigInteger convert byte[] differently?

这是Java代码:

new BigInteger("abc".getBytes()).toString();

结果是 6382179.

我想在 C# 中得到相同的结果,但是当我使用以下代码时:

(new System.Numerics.BigInteger(System.Text.Encoding.ASCII.GetBytes("abc"))).ToString();

我得到 6513249

如何在 C# 中以与 Java 相同的方式转换字符串?

C# 的 BigInteger 将字节数组视为小端:

Parameters

value Byte[]

An array of byte values in little-endian order.

而 Java 的 BigInteger 将字节数组视为大端:

Translates a byte array containing the two's-complement binary representation of a BigInteger into a BigInteger. The input array is assumed to be in big-endian byte-order: the most significant byte is in the zeroth element.

因此您需要 reverse the byte array 才能获得与使用其他语言相同的结果。

另请注意,Java 的 String.getBytes 使用默认编码,可能不是 ASCII。你应该使用

StandardCharsets.US_ASCII.encode("abc").array()
// or
"abc".getBytes(StandardCharsets.US_ASCII)

获取与 C# 代码相同的字节集。