nAviD
nAviD

Reputation: 3261

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

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?

Upvotes: 4

Views: 258

Answers (1)

Sweeper
Sweeper

Reputation: 271175

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.

Upvotes: 8

Related Questions