这是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# 代码相同的字节集。
关于java - 为什么 C# 和 Java BigInteger 转换 byte[] 的方式不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63203282/