Java BigInteger Calculate writeBigInteger(ByteArrayOutputStream baos, BigInteger bi)

Here you can find the source of writeBigInteger(ByteArrayOutputStream baos, BigInteger bi)

Description

write Big Integer

License

Open Source License

Declaration

public static void writeBigInteger(ByteArrayOutputStream baos, BigInteger bi) 

Method Source Code

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

import java.io.ByteArrayOutputStream;

import java.math.BigInteger;

public class Main {
    public static void writeBigInteger(ByteArrayOutputStream baos, BigInteger bi) {
        writeData(baos, bi.toByteArray());
    }//from ww  w  .  j a v a2s . c o  m

    public static void writeData(ByteArrayOutputStream baos, byte[] data) {
        writeLength(baos, data.length);
        baos.write(data, 0, data.length);
    }

    public static void writeLength(ByteArrayOutputStream baos, int len) {
        if (len < 0) {
            throw new RuntimeException("Invalid length < 0");
        }
        if (len <= 127) {
            //MSB = 0
            baos.write(len);
        } else if (len <= 16383) {
            // MSB = 10
            int lowbyte = len % 64;
            int highbyte = len / 64;
            baos.write(lowbyte + 128);
            baos.write(highbyte);
        } else if (len <= 2097151) {
            // MSB = 110
            int lowbyte = len % 32;
            int midbyte = (len / 32) % 256;
            int highbyte = len / 32 / 256;
            baos.write(lowbyte + 128 + 64);
            baos.write(midbyte);
            baos.write(highbyte);
        } else {
            throw new RuntimeException("Invalid length > 2^21-1");
        }
    }
}

Related

  1. unsignedBigIntergerToByteArray(BigInteger bigInteger)
  2. unsignedLongToBigInteger(byte[] source)
  3. unsignedToBigInteger(long l)
  4. writeBigInteger(BigInteger integer, DataOutputStream out)
  5. writeBigInteger(BigInteger m, int n, OutputStream os)
  6. writeBigInteger(ByteArrayOutputStream stream, BigInteger num)
  7. writeBigInteger(OutputStream output, BigInteger value)
  8. writeField(String tagName, BigInteger value, PrintWriter writer, int indent)
  9. writeLuposBigInteger(final BigInteger value, final int numberOfBits, final OutputStream os)