Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;
import java.io.InputStream;

public class Main {
    public static long readEncodedLength(InputStream input, int[] bytesReadOut) {
        try {
            int lbyte = input.read();
            if (lbyte == -1)
                return -1;
            if (lbyte == 0)
                throw new IllegalStateException("First length byte is 0");
            // there will always be 24 extra leading zeros from the first 3 bytes
            int nbytes = 1 + Integer.numberOfLeadingZeros(lbyte) - 24;

            // start with the first byte with the leading 1 masked out
            long value = lbyte ^ Integer.highestOneBit(lbyte);
            // read successive bytes, shifting current value each time (big-endian, most significant bytes first)
            for (int i = 1; i < nbytes; i++) {
                lbyte = input.read();
                if (lbyte == -1)
                    return -1;
                value = (value << 8) | lbyte;
            }
            if (bytesReadOut != null)
                bytesReadOut[0] = nbytes;
            return value;
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        }
    }

    public static long readEncodedLength(InputStream input) {
        return readEncodedLength(input, null);
    }
}