美文网首页
golang的可变长度编码

golang的可变长度编码

作者: 古则 | 来源:发表于2018-05-14 18:03 被阅读36次

可变长度编码 Variable-length encoding
先看PutUvarint源码

func PutUvarint(buf []byte, x uint64) int {
    i := 0
    for x >= 0x80 {
        buf[i] = byte(x) | 0x80
        x >>= 7
        i++
    }
    buf[i] = byte(x)
    return i + 1
}

ReadUvarint源码

// ReadUvarint reads an encoded unsigned integer from r and returns it as a uint64.
func ReadUvarint(r io.ByteReader) (uint64, error) {
    var x uint64
    var s uint
    for i := 0; ; i++ {
        b, err := r.ReadByte()
        if err != nil {
            return x, err
        }
        if b < 0x80 {
            if i > 9 || i == 9 && b > 1 {
                return x, overflow
            }
            return x | uint64(b)<<s, nil
        }
        x |= uint64(b&0x7f) << s
        s += 7
    }
}

相关文章

网友评论

      本文标题:golang的可变长度编码

      本文链接:https://www.haomeiwen.com/subject/pivjdftx.html