Convert byte array of ASCII numeric characters to int using GO language

@Volker is right in his comment, you don't have a binary number in your array, you have an ASCII string. Yet, you try to decode it as binary. Note there's no need to validate any input (maybe except the length) if you were dealing with binary number, as all single byte values are valid.

@Ainar-G gave you a way of converting ASCII number into integer.

Compare these two approaches: (http://play.golang.org/p/_wufZ4P_aE)

buf := []byte{54, 54, 49, 49}

x, _ := strconv.Atoi(string(buf))
fmt.Println(x)

This prints 6611; but look at this:

var y int32
_ = binary.Read(bytes.NewReader(buf), binary.BigEndian, &y)
fmt.Println(y)

This prints 909521201, so exactly what you got (and didn't expect). As a side note, you're manually decoding it as BigEndian, so this is not "such a simple conversion" at the end, because there're some more factors to consider.

Your handcrafted conversion from ASCII would look more or less as follows:

var x int32
for _, c := range in {
    x = x*10 + int32(c - '0')
}
return x

But using strconv is the way to go.


Convert your bytes to string and use strconv.Atoi.

b := []byte{54, 54, 49, 49}
s := string(b)
i, err := strconv.Atoi(s)
if err != nil {
    panic(err)
}
fmt.Println(i)

Playground: http://play.golang.org/p/NiobWHZ9gd