dqjgf0982 2015-01-20 01:55
浏览 4

Go Varint返回预期值的一半

Why is the output of this code:

package main

import (
    "fmt"
    "encoding/binary"
)

func main() {
    var myByte byte = 18
    array := []byte{myByte}
    val, n := binary.Varint(array)
    fmt.Printf("value: %d, num bytes: %d
", val, n)
}

value: 9, num bytes: 1 instead of value: 18, num bytes: 1

It probably has something to do with two's complement, but I'm not seeing how.

  • 写回答

2条回答 默认 最新

  • dsyk33753 2015-01-20 02:09
    关注

    Yes. Check this modified version: http://play.golang.org/p/AyP2a4gue8

    package main
    
    import (
        "encoding/binary"
        "fmt"
    )
    
    func main() {
        for i := 0; i < 100; i++ {
            var myByte byte = byte(i)
            array := []byte{myByte}
            val, n := binary.Varint(array)
            fmt.Printf("int %d value: %d, num bytes: %d
    ", i, val, n)
    
        }    
    }
    

    which produces the following output:

    int 0 value: 0, num bytes: 1
    int 1 value: -1, num bytes: 1
    int 2 value: 1, num bytes: 1
    int 3 value: -2, num bytes: 1
    int 4 value: 2, num bytes: 1
    int 5 value: -3, num bytes: 1
    int 6 value: 3, num bytes: 1
    int 7 value: -4, num bytes: 1
    int 8 value: 4, num bytes: 1
    int 9 value: -5, num bytes: 1
    int 10 value: 5, num bytes: 1
    int 11 value: -6, num bytes: 1
    int 12 value: 6, num bytes: 1
    int 13 value: -7, num bytes: 1
    int 14 value: 7, num bytes: 1
    int 15 value: -8, num bytes: 1
    int 16 value: 8, num bytes: 1
    int 17 value: -9, num bytes: 1
    int 18 value: 9, num bytes: 1
    

    You can see "zig-zagging" between the negatives and positives. This is because, according to the documented binary format, varints use "zig-zag" encoding so that values of small absolute value are encoded with small values.

    评论

报告相同问题?