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
+8k Golang : Handle Palindrome string with case sensitivity and unicode
+18.4k Golang : Logging with logrus
+13.8k Golang : unknown escape sequence error
+5.8k Unix/Linux : How to test user agents blocked successfully ?
+5.4k Golang : Reclaim memory occupied by make() example
+8.1k Golang : Check from web if Go application is running or not
+9.3k Golang : How to get username from email address
+30.4k Golang : Generate random string
+36.3k Golang : Convert(cast) int64 to string
+28k Golang : Move file to another directory
+5k Google : Block or disable caching of your website content
+11.7k Golang : Secure file deletion with wipe example