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

Java examples for java.math:BigInteger

Description

Copy a BigInteger into a byte array.

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 {
        BigInteger bi = new BigInteger("1234");
        byte[] a = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        copy_into_byte_array(bi, a);
    }//from w  w  w.j a  va2 s  .  c  om

    /**
     * 
     * Copy a BigInteger into a byte array. This is a bit more tricky
     * than just copying the result of {@link BigInteger#toByteArray}.
     * First, the argument array {@code a} might need some zero
     * padding and second, {@link BigInteger#toByteArray} might have a
     * leading zero that does not fit into {@code a}.
     * <P>
     *
     * Asserts that the BigInteger {@code bi}, with leading zeros
     * removed, fits into {@code a}.
     * 
     * @param bi the source BigInteger 
     * @param a the destination array
     */
    public static void copy_into_byte_array(BigInteger bi, byte[] a) {
        byte[] bia = bi.toByteArray();
        assert bia.length <= a.length
                || (bia.length == a.length + 1 && bia[0] == 0);
        for (int i = 0; i < a.length - bia.length; i++)
            a[i] = 0;
        System.arraycopy(bia, bia.length == a.length + 1 ? 1 : 0, a,
                bia.length == a.length + 1 ? 0 : a.length - bia.length,
                bia.length == a.length + 1 ? a.length : bia.length);
        return;
    }
}

Related Tutorials