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

huangapple go评论68阅读模式
英文:

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相同的方式转换字符串?

英文:

This is Java code:

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

and the result is 6382179.

I want the same result in C# but when I use the following code:

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

I get 6513249.

How do I convert the string in C# the same way as Java?

答案1

得分: 8

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

> 参数
>
> value Byte[]
>
> 以小端序排列的字节值数组。

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

> 将包含 BigInteger 的二进制补码表示的字节数组转换为 BigInteger。假定输入数组以大端字节顺序排列:最重要的字节位于零元素。

因此,您需要反转字节数组以获得与另一种语言中相同的结果。

还要注意,Java的 String.getBytes 使用默认编码,这可能不是ASCII。您应该使用

StandardCharsets.US_ASCII.encode("abc").array()
// 或者
"abc".getBytes(StandardCharsets.US_ASCII)

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

英文:

C#'s BigInteger treats the byte array as little-endian:

> Parameters
>
> value Byte[]
>
> An array of byte values in little-endian order.

Whereas Java's BigInteger treats the byte array as big-endian:

> 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.

So you need to reverse the byte array to get the same result as you do in the other language.

Also note that Java's String.getBytes uses the default encoding, which might not be ASCII. You should use

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

to get the same set of bytes as the C# code.

huangapple
  • 本文由 发表于 2020年8月1日 16:31:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/63203282.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定