I see some answers to exactly the same question I have: How to convert Byte array to int in GO programming language?
I wrote below function to convert byte array to int
func convertByteToInt(in []byte) int32 {
return (int32(in[0]) << 24 | int32(in[1]) << 16 | int32(in[2]) << 8 | int32(in[3]))
}
Before that, I made sure that byte array has correct(base 256) values. in[0] = 54 (ASCII for 6), in[1] = 54 (ASCII for 6), in[2] = 49 (ASCII for 1), in[3] = 49 (ASCII for 1).
So I am expecting to retrieve integer 6611 value from byte array, but I ended up getting 909521201. I fail to understand what is exactly going on in such a simple conversion. Can anyone flash some light?
THanks
The byte type in Golang is an alias for the unsigned integer 8 type ( uint8 ). The byte type is only used to semantically distinguish between an unsigned integer 8 and a byte. The range of a byte is 0 to 255 (same as uint8 ).
Solution: To get the ASCII value of a character, simply type cast the character with int() function and make sure the character is a rune instead of type string . To revert it back or to convert integer ASCII value to a character, type cast the integer with string() function.
Like byte type, Go has another integer type rune . It is aliases for int32 (4 bytes) data types and is equal to int32 in all ways.
The byte data type represents ASCII characters while the rune data type represents a more broader set of Unicode characters that are encoded in UTF-8 format. In Go, Characters are expressed by enclosing them in single quotes like this: 'a'.
@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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With