CodeToolProCodeToolPro
GitHub

VarInt Encoder / Decoder

Encode Number to Varint

  • Decode Varint to Number

    Base-128 Varint: Used by Protocol Buffers. Each byte uses 7 bits for data and 1 bit (MSB) to indicate if more bytes follow. Numbers 0-127 use 1 byte, 128-16383 use 2 bytes, etc.

    技术详情

    Varint 编解码器的工作原理

    工具功能

    Varint(Variable-length Integer)编解码器可在标准整数与 varint 编码之间互相转换。Varint 是一种变长整数编码方式,使用 1-10 个字节表示一个 64 位整数,值越小占用的字节数越少。该技术是 Protobuf、gRPC 等序列化协议的基础,也用于 WebSocket 等网络协议中。该工具帮助理解 varint 编码机制和验证编解码正确性。


    常见开发者使用场景

    Varint 编码在网络协议和序列化中广泛应用:Protobuf 使用 varint 编码所有整数类型字段、WebSocket 帧的 payload 长度使用扩展的 varint 编码、SQLite 数据库内部使用 varint 存储整数、以及自定义网络协议中使用 varint 减少小整数的传输开销。开发者在实现协议栈或解析二进制数据时通常需要处理 varint 编解码。

    深入理解 varint 后,可以结合 Protobuf 编解码器 查看完整的序列化流程。字节序转换器 处理二进制数据的字节序转换。进制转换器 可在不同进制之间转换 varint 值。


    技术原理/相关概念

    Varint 编码的核心思想是用每个字节的最高位(MSB)作为继续标志:MSB=1 表示后面还有更多字节,MSB=0 表示这是最后一个字节。剩余的 7 位用于组值,多个字节的值按小端序拼接。例如,300 的 varint 编码为 0xAC 0x02:0xAC = 10101100(MSB=1,值=0101100),0x02 = 00000010(MSB=0,值=0000010);拼接值 = 0000010 0101100 = 300。有符号整数使用 zigzag 编码:将有符号值映射为无符号值(0→0, -1→1, 1→2, -2→3...),再进行 varint 编码。


    常见陷阱与注意事项

    • 溢出处理:varint 理论上可编码任意大整数,但 Protobuf 等协议限制为 64 位(最大 10 字节)。超过 10 字节的 varint 应视为无效。
    • Zigzag 与标准区别:有符号整数需先 zigzag 编码再 varint,直接对有符号值进行 varint 编码会导致不兼容。
    • 小端序:varint 组值使用小端序,与常见的网络大端序不同,解析时需要特别注意字节序。
    • 负数膨胀:不进行 zigzag 编码的负数(如 int32)会占用 10 个字节(带符号扩展),因此 sint32 和 sint64 类型使用 zigzag 优化。

    何时使用此工具而非代码

    在学习 Protobuf 编码机制、调试网络协议包或验证自定义 varint 实现时使用此工具。适合网络协议开发者和系统程序员理解二进制编码。对于在代码中集成 varint 处理,推荐使用 Protobuf 库或位运算直接实现(C 语言宏、Rust 的 integer-encoding crate),它们提供内联优化和零拷贝处理。

    How to Use VarInt Encoder / Decoder

    1. 1Enter your text or data into the input field
    2. 2Select the encoding or decoding direction
    3. 3View the encoded or decoded result instantly
    4. 4Copy the output for use in your application

    Frequently Asked Questions

    • Is the encoding/decoding process reversible?

      Yes. All encoding formats supported here are lossless and fully reversible. Decode back to the original data at any time with 100% fidelity.

    • Is VarInt Encoder / Decoder free?

      Yes, 100% free. No registration, no credit card required. All tools are freely available for developers worldwide.

    • Does this tool upload my data to any server?

      No. All processing runs locally in your browser using client-side JavaScript. Your input data, code, or files never leave your device. We do not store, log, or transmit any user data.