Java BigInteger from Stream readBigInteger(ByteArrayInputStream bais)

Here you can find the source of readBigInteger(ByteArrayInputStream bais)

Description

read Big Integer

License

Open Source License

Declaration

public static BigInteger readBigInteger(ByteArrayInputStream bais) 

Method Source Code


//package com.java2s;
//* Licensed Materials - Property of IBM, Miracle A/S, and            *

import java.io.ByteArrayInputStream;

import java.math.BigInteger;

public class Main {
    public static BigInteger readBigInteger(ByteArrayInputStream bais) {
        return new BigInteger(readData(bais));
    }//from   ww  w. java 2  s .c o  m

    public static byte[] readData(ByteArrayInputStream bais) {
        int len = getLength(bais);
        byte[] data = new byte[len];
        bais.read(data, 0, len);
        return data;
    }

    public static int getLength(ByteArrayInputStream bais) {
        int lowbyte = bais.read();
        if ((lowbyte & 128) == 0) {
            // MSB = 0
            return lowbyte;
        } else if ((lowbyte & 64) == 0) {
            // MSB = 10
            lowbyte -= 128;
            int highbyte = bais.read();
            return lowbyte + highbyte * 64;
        } else if ((lowbyte & 32) == 0) {
            // MSB = 110
            lowbyte -= 128 + 64;
            int midbyte = bais.read();
            int highbyte = bais.read();
            return lowbyte + midbyte * 32 + highbyte * 32 * 256;
        } else {
            throw new RuntimeException("Cannot parse length");
        }
    }
}

Related

  1. readBigInteger(DataInputStream dis)
  2. readBigInteger(InputStream input)
  3. readBigInteger(int n, DataInput dis)
  4. readLineAsBigInteger(BufferedReader br)