Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 662
nAviD Avatar asked Jan 25 '23 20:01

nAviD


1 Answers

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.

like image 186
Sweeper Avatar answered Feb 02 '23 07:02

Sweeper