I have come across many sample code whenever we try to convert string to int we use :
parseValue, err := strconv.ParseInt(value, 10, 64)
So the code above ParseInt()
has three arguments. from the documentation code :
func ParseInt(s string, base int, bitSize int) (i int64, err error) {
I tried to understand the base int
here so I change the value from 0 to 16. PlayGolang.
The result is ok when the input are 0
and 10
. Number other that 0
and 10
are panic. I still confused and not understand. Can someone explain what base
is used for in ParseInt()
?
You are converting a string to an integer. The method is asking you for the base (number system) the string is in. You can learn more about number systems here: https://en.wikipedia.org/wiki/Radix
For example (using your code snippet provided here):
var s string = "1111" // This string is in binary (Base 2)
i, err := strconv.ParseInt(s, 2, 64) // Give the base as 2
Result:
Hello, 15 with type int64!