Converting single-byte slice to int

In my program I need to read data from the byte array, sometimes I need to read single byte, sometimes 2, 4 or 8 bytes. Then these bytes should be converted into “normal” integer values.

For 2, 4 and 8 bytes I can use “encodings/binary” package and its binary.BigEndian.Uint16(), binary.BigEndian.Uint32() and binary.BigEndian.Uint64() and then cast values to int if necessary.

But what is the recommended way to convert single-byte slice to int? I use following code now, but now sure if this is a correct way

import (
    "bytes"
    "encoding/binary"
)

data := []byte{0, 0, 0, 0, 0, 0, 0, 73, 8, 2, 0, 0, 1}
var a byte
err := binary.Read(bytes.NewReader(data[8:9]), binary.BigEndian, &a)
r :=int(a)

Probably there is an unified way to convert slices to integers which works with slices of different length?

It’s correct but rather convoluted.
The big endian and little endian representations of a single byte are the same.
So you could just do:

var r = int(data[8])
1 Like

Thanks!

Is there unified way to convert slice of any length (1, 2, 4, or 8 bytes) to integer? I tried to use
binary.ReadVarint([]byte) but it does not work with single-byte slices. I’m trying to avoid adding condition and different handling inside the loop just for single-byte slices.

You can pad and use Uint64, or you can do it manually: https://play.golang.org/p/eECOVBhWmlH

Note that the results are nonsensical for values over four bytes as int in the playground is 32 bits. Also, sign handling requires consideration.

1 Like

Thanks a lot!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.