How to Read a Variable-Length Integer from an InputStream in Java

Question

What is the process for reading a variable-length integer from an InputStream in Java?

import java.io.*;

public class VariableLengthIntegerReader {
    public static int readVarInt(InputStream input) throws IOException {
        int value = 0;
        int bytesRead = 0;
        int currentByte;

        do {
            currentByte = input.read();
            value |= (currentByte & 0x7F) << (7 * bytesRead);
            bytesRead++;
            if (bytesRead > 5) {
                throw new IOException("VarInt is too long");
            }
        } while ((currentByte & 0x80) != 0);

        return value;
    }
}

Answer

Reading a variable-length integer from an InputStream requires understanding how such integers are encoded. These integers are commonly represented using a byte format where the most significant bit indicates whether the next byte should be read as part of the integer value.

import java.io.*;

public class VariableLengthIntegerReader {
    public static int readVarInt(InputStream input) throws IOException {
        int value = 0;
        int bytesRead = 0;
        int currentByte;

        do {
            currentByte = input.read();
            value |= (currentByte & 0x7F) << (7 * bytesRead);
            bytesRead++;
            if (bytesRead > 5) {
                throw new IOException("VarInt is too long");
            }
        } while ((currentByte & 0x80) != 0);

        return value;
    }
}

Causes

  • Variable-length integers can take up to 5 bytes to represent. Bytes are encoded such that the highest bit (bit 7) indicates there are more bytes to read.
  • Improper handling or assumption of fixed-length integers might lead to incorrect values being interpreted.

Solutions

  • Implement a reading loop that continues until a byte with the highest bit set to 0 is encountered.
  • Use bitwise operations to construct the integer from its byte components.
  • Ensure to throw an exception if the integer exceeds the expected length.

Common Mistakes

Mistake: Assuming the integer will always fit into 4 bytes and not handling longer variable-length integers.

Solution: Implement proper checks and potentially throw exceptions if the length exceeds expected values.

Mistake: Not handling input stream closure correctly can lead to resource leaks.

Solution: Ensure to close InputStreams appropriately in a finally block or use try-with-resources.

Helpers

  • Java InputStream variable length integer
  • read variable-length integer Java
  • InputStream read integer Java
  • Java read from InputStream
  • variable-length integers Java

Related Questions

⦿How to Split a String with a Recurring Delimiter in Java and Handle Incomplete Messages

Learn how to split strings with recurring delimiters in Java and effectively manage broken messages with expert tips and examples.

⦿How to Extract a Substring from a String with Repeated Characters?

Learn effective methods for extracting substrings from a string containing repeated characters. Explore solutions and code examples.

⦿How to Retrieve SimOperatorName for a Dual SIM Android Device

Learn how to get the SimOperatorName for dual SIM Android phones with clear steps and code examples.

⦿How to Create a Custom Splash Screen for Your Eclipse Plugin (Non-RCP)

Learn how to design and implement a custom splash screen for your Eclipse plugin without using RCP. Stepbystep guide with code examples.

⦿How to Use DELETE ... RETURNING rowid with JOOQ

Discover how to implement DELETE ... RETURNING rowid in JOOQ effectively. Learn common mistakes and solutions for optimal database operations.

⦿How to Resolve Sonar Job Failures During Analysis in Jenkins

Learn how to troubleshoot and resolve Sonar job failures during analysis in Jenkins with expert tips and solutions.

⦿Understanding the Precedence of Ambiguous Accessors in JSP Expression Language

Learn about the ambiguity in JSP Expression Language accessors and how boolean and int types interact with code examples and best practices.

⦿How to Use a Private Key String with JSCH Instead of a File Path in Java

Learn how to pass a private key string to JSCH instead of a file path for Java SSH connections. Stepbystep guide with code examples included.

⦿How to Implement Custom Injections for Log4j2?

Learn how to create and implement custom injections in Log4j2 to enhance logging functionality in your Java applications.

⦿How to Reference Enum Items in Java

Learn how to reference enum items in Java with detailed explanations code snippets and common mistakes to avoid.

© Copyright 2025 - CodingTechRoom.com