Java (BigInteger array of bytes)

I use the following code to create BigIntegerfrom a hexadecimal string and printing for output.

package javaapplication2;

import java.math.BigInteger;
import javax.xml.bind.DatatypeConverter;

public class JavaApplication2 {
    public static void main(String[] args) {
        // Number in hexadecimal form
        String HexString = "e04fd020ea3a6910a2d808002b30309d";
        // Convertation from string to byte array
        byte[] ByteArray = toByteArray(HexString);
        // Creation of BigInteger from byte array
        BigInteger BigNumber = new BigInteger(ByteArray);
        // Print result
        System.out.print(BigNumber + "\n");
    }
    public static String toHexString(byte[] array) {
        return DatatypeConverter.printHexBinary(array);
    }

    public static byte[] toByteArray(String s) {
        return DatatypeConverter.parseHexBinary(s);
    }
}

After this code I get the following result:

-42120883064304190395265794005525319523

But I expect to see this result:

298161483856634273068108813426242891933

What am I doing wrong?

+4
source share
2 answers

You pass an array of bytes where the first byte is set upper bits, which makes it negative. From designer documentation :

It translates the array of bytes containing the binary representation of a binary complement BigInteger BigInteger. It is assumed that the input array is located in a large byte order byte: the most significant byte is in the zeroth element.

.

, :

  • "00", 0
  • BigInteger(String, int), "-" . (, 16 .)
  • BigInteger(int, byte[]), 1 signum

, , , . , .

+12

BigInteger bigInt = new BigInteger(HexString, 16);
+3

All Articles