Golang encoding/binary.Uvarint() function examples
package encoding/binary
Uvarint decodes a uint64 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 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.Uvarint() 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.Uvarint(emptybuf)
fmt.Println(num, ret)
num, ret = binary.Uvarint(buf)
fmt.Println(num, ret)
num, ret = binary.Uvarint(overflowbuf)
fmt.Println(num, ret)
}
Output :
0 0
1161981756374523920 9
0 -11
Example 2 :
func decodeBlockHandle(src []byte) (blockHandle, int) {
offset, n := binary.Uvarint(src)
length, m := binary.Uvarint(src[n:])
if n == 0 || m == 0 {
return blockHandle{}, 0
}
return blockHandle{offset, length}, n + m
}
References :
http://golang.org/pkg/encoding/binary/#Uvarint
https://github.com/syndtr/goleveldb/blob/master/leveldb/table/table.go
Advertisement
Something interesting
Tutorials
+9.2k Golang : does not implement flag.Value (missing Set method)
+8.9k Golang : Sort lines of text example
+6.4k CodeIgniter : form input set_value cause " to become & quot
+18.5k Golang : Send email with attachment
+14.8k Golang : Normalize unicode strings for comparison purpose
+10.6k Golang : ISO8601 Duration Parser example
+9.8k Golang : Qt get screen resolution and display on center example
+14.3k Golang : Recombine chunked files example
+22.5k Golang : Convert Unix timestamp to UTC timestamp
+9.3k Golang : Timeout example
+7k Golang : constant 20013 overflows byte error message
+8.2k Golang : Qt splash screen with delay example