Convert a byte array into a BigInteger . - Java java.math

Java examples for java.math:BigInteger

Description

Convert a byte array into a BigInteger .

Demo Code

// This program is free software; you can redistribute it and/or
//package com.java2s;

import java.math.BigInteger;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] a = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(from_byte_array(a));
    }//from ww  w  . jav  a  2  s.c  om

    /**
     * 
     * Convert a byte array into a {@link BigInteger}. This is just as
     * {@link BigInteger#BigInteger(byte[])} but does not produce
     * negative BigIntegers if the first bit in {@code a} is set.
     * 
     * @param a source byte array
     * @return positive BigInteger with the value of {@code a}
     */
    public static BigInteger from_byte_array(byte[] a) {
        byte[] a0 = new byte[a.length + 1];
        a0[0] = 0;
        System.arraycopy(a, 0, a0, 1, a.length);
        return new BigInteger(a0);
    }
}

Related Tutorials