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
+5.8k Cash Flow : 50 days to pay your credit card debt
+14.4k Golang : On enumeration
+14.2k Golang : Chunk split or divide a string into smaller chunk example
+17.6k Golang : Parse date string and convert to dd-mm-yyyy format
+5.2k PHP : See installed compiled-in-modules
+8.4k Golang : How to check if input string is a word?
+8.8k Golang : HTTP Routing with Goji example
+24.5k Golang : GORM read from database example
+26.6k Golang : Encrypt and decrypt data with AES crypto
+8.6k Golang : Progress bar with ∎ character
+10k Golang : Convert octal value to string to deal with leading zero problem