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 :
Advertisement
Something interesting
Tutorials
+6.1k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+9.8k Golang : Resumable upload to Google Drive(RESTful) example
+8.3k Swift : Convert (cast) Character to Integer?
+14.8k Golang : Get URI segments by number and assign as variable example
+27.9k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+6.3k Javascript : Generate random key with specific length
+4.5k Java : Generate multiplication table example
+8.6k Golang : Another camera capture GUI application with GTK and OpenCV
+10k Golang : Convert octal value to string to deal with leading zero problem
+9k Golang : Capture text return from exec function example
+7.9k Swift : Convert (cast) String to Float
+9.7k Golang : Format strings to SEO friendly URL example