Here you can find the source of readBigInteger(InputStream input)
Parameter | Description |
---|---|
input | the stream to read from |
Parameter | Description |
---|---|
IOException | an exception |
static BigInteger readBigInteger(InputStream input) throws IOException
//package com.java2s; /**// w ww. j a v a2 s . com * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; public class Main { /** * Read the signed arbitrary sized BigInteger BigInteger in vint format * @param input the stream to read from * @return the read BigInteger * @throws IOException */ static BigInteger readBigInteger(InputStream input) throws IOException { BigInteger result = BigInteger.ZERO; long work = 0; int offset = 0; long b; do { b = input.read(); if (b == -1) { throw new EOFException("Reading BigInteger past EOF from " + input); } work |= (0x7f & b) << (offset % 63); offset += 7; // if we've read 63 bits, roll them into the result if (offset == 63) { result = BigInteger.valueOf(work); work = 0; } else if (offset % 63 == 0) { result = result.or(BigInteger.valueOf(work).shiftLeft(offset - 63)); work = 0; } } while (b >= 0x80); if (work != 0) { result = result.or(BigInteger.valueOf(work).shiftLeft((offset / 63) * 63)); } // convert back to a signed number boolean isNegative = result.testBit(0); if (isNegative) { result = result.add(BigInteger.ONE); result = result.negate(); } result = result.shiftRight(1); return result; } }