Golang encoding/binary.Varint() function examples

package encoding/binary

Varint decodes an int64 from buf (1st parameter) and returns that value and the number of bytes read (> 0). If an error occurred, the value is 0 and the number of bytes n is <= 0 with the following meaning:

n == 0: buf too small

n < 0: value larger than 64 bits (overflow) and -n is the number of bytes read

Golang encoding/binary.Varint() function usage examples

Example 1 :

 package main

 import (
 "encoding/binary"
 "fmt"
 )

 func main() {
 var emptybuf []byte
 var buf []byte = []byte{144, 192, 192, 129, 132, 136, 140, 144, 16, 0, 1, 1}
 var overflowbuf []byte = []byte{144, 192, 192, 129, 132, 136, 140, 144, 192, 192, 1, 1}

 num, ret := binary.Varint(emptybuf)
 fmt.Println(num, ret)

 num, ret = binary.Varint(buf)
 fmt.Println(num, ret)

 num, ret = binary.Varint(overflowbuf)
 fmt.Println(num, ret)
 }

Output :

0 0

580990878187261960 9

0 -11

Example 2 :

 func randUInt64() uint64 {
 buf, _ := randBytes(8)
 res, _ := binary.Varint(buf)
 return uint64(res)
 }

References :

http://golang.org/pkg/encoding/binary/#Varint

Advertisement