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?
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.