Jenia Be Nice Please
Jenia Be Nice Please

Reputation: 2703

How to convert a []byte to a integer

I'm trying to convert a slice of bytes to an integer and it just does not work:

https://play.golang.org/p/61Uhllz_qm7

For two perfectly different slices of bytes, I get the same uint64 when I use this algorithm:

func idFromPacket(response []byte) uint64 {
    fmt.Printf("The slice is [%v]\n", response)
    var id uint64
    reader := bytes.NewReader(response)
    binary.Read(reader, binary.BigEndian, &id)
    fmt.Printf("The id is [%d]\n", id)
    return id
}

Can someone please tell me, why for different []byte input to idFromPacket I get the same output?

Thanks

Upvotes: 0

Views: 401

Answers (2)

zerkms
zerkms

Reputation: 255155

Can someone please tell me, why for different []byte input to idFromPacket I get the same output?

Because uint64 is 64 bits (8 bytes) long and you're passing 80 bits (10 bytes).

That is 2 bytes wider than necessary.

Then binary.Read reads first 8 bytes, which are all zeroes in both inputs and returns you 0 in both cases as expected.

Upvotes: 2

MarvinJWendt
MarvinJWendt

Reputation: 2694

For your use case, you can replace your function with this one:

func idFromPacket(response []byte) uint64 {
    fmt.Printf("The slice is [%v]\n", response)
    var id uint64
    for _, v := range response {
        id <<= 8
        id |= uint64(v)
    }
    fmt.Printf("The id is [%v]\n", id)
    return id
}

Upvotes: 1

Related Questions