Binary files are encoded with a variable length prefix that tells you the size of the string. - Java java.lang

Java examples for java.lang:int Binary

Description

Binary files are encoded with a variable length prefix that tells you the size of the string.

Demo Code


//package com.java2s;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    /**//  w w w  .  j a  va  2 s. co m
     * Binary files are encoded with a variable length prefix that tells you
     * the size of the string. The prefix is encoded in a 7bit format where the
     * 8th bit tells you if you should continue. If the 8th bit is set it means
     * you need to read the next byte.
     * @param bytes
     * @return
     */
    public static int getStringLength(final InputStream is)
            throws IOException {
        int count = 0;
        int shift = 0;
        boolean more = true;
        while (more) {
            byte b = (byte) is.read();
            count |= (b & 0x7F) << shift;
            shift += 7;
            if ((b & 0x80) == 0) {
                more = false;
            }
        }
        return count;
    }
}

Related Tutorials