Java BigInteger to toPaddedBytes(BigInteger bi, int length)

Here you can find the source of toPaddedBytes(BigInteger bi, int length)

Description

to Padded Bytes

License

Apache License

Declaration

public static byte[] toPaddedBytes(BigInteger bi, int length) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.math.BigInteger;

public class Main {
    public static byte[] toPaddedBytes(int i) {
        byte[] b = new byte[4];
        b[0] = (byte) (i >>> 24);
        b[1] = (byte) (i >>> 16);
        b[2] = (byte) (i >>> 8);
        b[3] = (byte) (i);
        return b;
    }//from   w w  w  .jav a2 s.co m

    public static byte[] toPaddedBytes(long l) {
        byte[] b = new byte[8];
        b[0] = (byte) (l >>> 56);
        b[1] = (byte) (l >>> 48);
        b[2] = (byte) (l >>> 40);
        b[3] = (byte) (l >>> 32);
        b[4] = (byte) (l >>> 24);
        b[5] = (byte) (l >>> 16);
        b[6] = (byte) (l >>> 8);
        b[7] = (byte) (l);
        return b;
    }

    public static byte[] toPaddedBytes(BigInteger bi, int length) {
        byte[] biBytes = bi.toByteArray();
        int diff = length - biBytes.length;
        if (diff < 0)
            throw new NumberFormatException("BigInteger value is bigger than requested " + length + " bytes");
        byte[] out = new byte[length];
        System.arraycopy(biBytes, 0, out, diff, biBytes.length);
        return out;
    }

    public static byte[] toPaddedBytes(long l, int length) {
        byte[] lBytes = toBytes(l);
        int diff = length - lBytes.length;
        if (diff < 0)
            throw new NumberFormatException("long value is bigger than requested " + length + " bytes");
        byte[] out = new byte[length];
        System.arraycopy(lBytes, 0, out, diff, lBytes.length);
        return out;
    }

    public static byte[] toBytes(int i) {
        int step = 8;
        for (; (i >>> step) > 0 && step < 32; step += 8)
            ;
        byte[] b = new byte[step / 8];
        for (int x = 0, move = step - 8; x < (step / 8); x++, move -= 8) {
            b[x] = (byte) (i >>> move);
        }
        return b;
    }

    public static byte[] toBytes(long l) {
        int step = 8;
        for (; (l >>> step) > 0 && step < 64; step += 8)
            ;
        byte[] b = new byte[step / 8];
        for (int x = 0, move = step - 8; x < (step / 8); x++, move -= 8) {
            b[x] = (byte) (l >>> move);
        }
        return b;
    }
}

Related

  1. toInteger(BigInteger bi)
  2. toInteger(BigInteger integer)
  3. toIntegerBytes(final BigInteger bigInt)
  4. toMinimalByteArray(BigInteger value)
  5. toObject(BigInteger x)
  6. toPushbackReader(BigInteger x)
  7. toStr(BigInteger number)
  8. toString(BigInteger bi)
  9. toString(BigInteger[] vector)