You're using the variable width encoding. The number of bytes of a variable 
width encoded int64 will depend on the magnitude of the value. If you use 
binary.BigEndian or binary.LittleEndian you can use the PutUint64 method 
which will always be 8 bytes.

On Monday, February 27, 2017 at 11:27:07 AM UTC-7, Guillermo Estrada wrote:
>
> Hey Gophers! I'm having a bit of trouble understanding something about the 
> standard library, I'm pretty sure either it is not wrong, or there is a 
> reason behind it, but either way I don't understand which one. As the title 
> suggests, I'm using encode/binary to write a int64 into a byte slice, but 
> apparently... it won't fit into an 8 byte slice... (64 bits right?). Well, 
> here's a bit of code:
>
> import (
> "encoding/binary"
> "fmt"
> "time"
> )
>
> func main() {
> t := time.Now()
> b1 := make([]byte, 10)
> b2 := make([]byte, 10)
> u1 := binary.PutVarint(b1, t.Unix())
> u2 := binary.PutVarint(b2, t.UnixNano())
> i1, v1 := binary.Varint(b1)
> i2, v2 := binary.Varint(b2)
> fmt.Println("Unix:", t.Unix(), b1, "/", u1, "->", i1, "/", v1)
> fmt.Println("UnixNano:", t.UnixNano(), b2, "/", u2, "->", i2, "/", v2)
> }
>
>
> *Sample output:*
>
> Unix: 1488220019 [230 189 163 139 11 0 0 0 0 0] /* 5* -> 1488220019 / *5*
> UnixNano: 1488220019858895600 [224 203 131 245 163 142 156 167 41 0] / *9* 
> -> 1488220019858895600 / *9* 
>
> As you can see, both ways reports 5/9 bytes being written in and from the 
> byte slice. I'm trying to use Unix times as ordered keys in a DB, I can 
> totally use the 9 byte slices, I just don't understand why a 64 bit number 
> would write 9 bytes (or a 32bit into 5 for Unix()). Is there something I'm 
> missing??
>
> Thank you for your time!
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to