How to use the strconv.ParseInt() function in Golang
Golang strconv.ParseInt() Function
The strconv package’s ParseInt() function converts the given string s to an integer value i in the provided base (0, 2 to 36) and bit size (0 to 64).
Note: To convert as a positive or negative integer, the given
stringmust begin with a leading sign, such as+or-.
Syntax
func ParseInt(s string, base int, bitSize int) (i int64, err error)
Parameter
-
s: String value to be converted in an integer number. -
base: The base value of the given value. It can range from0,2to36. -
bitSize: It specifies the integer type, such as,int(0),int8(8),int16(16),int32(32), andint64(64).
Return type
The returned value is int, error type.
Return value
The strconv.ParseInt() function returns the integer number converted from the given string.
Code
The following code shows how to implement the strconv.ParseInt() function in Golang:
// Golang program// strconv.ParseInt() Functionpackage mainimport ("fmt""strconv")func main() {// delare variable of type stringvar str string// assigning valuestr = "1041"// ParseInt() converts variable str to a integer number// with the specified base and bitSize// diplays resultfmt.Println(strconv.ParseInt(str, 10, 32))fmt.Println(strconv.ParseInt(str, 2, 64))fmt.Println()// reassigning valuestr = "-1041"// ParseFloat() converts variable str to a integer number// with the specified base and bitSize// diplays resultfmt.Println(strconv.ParseInt(str, 8, 32))fmt.Println(strconv.ParseInt(str, 16, 64))fmt.Println()// reassigning valuestr = "1Shots12"// ParseInt() converts variable str to a integer number// with the specified base and bitSize// diplays resultfmt.Println(strconv.ParseInt(str, 2, 32))fmt.Println(strconv.ParseInt(str, 16, 64))fmt.Println()// reassigning valuestr = "00101110111111"// ParseFloat() converts variable str to a integer number// with the specified base and bitSize// diplays resultfmt.Println(strconv.ParseInt(str, 16, 32)) // throw out of range errorfmt.Println(strconv.ParseInt(str, 16, 64))fmt.Println()}
Explanation
-
Line 1: We add the
mainpackage. -
Lines 3 to 6: We import necessary packages in Golang project.
-
Lines 11 to 21: We define the
main()function, variablestrofstringtype and assign a value to it, and then converts variablestrto an integer number using theParseInt()function with the specified base and bitSize. Finally, the result is displayed.