Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
strconv
communitycreator

How to use the strconv.ParseInt() function in Golang

Maria Elijah

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 string must 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 from 0, 2 to 36.

  • bitSize: It specifies the integer type, such as, int(0), int8(8), int16(16), int32(32), and int64(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() Function

package main

import (
	"fmt"
	"strconv"
)

func main() {
	// delare variable of type string
	var str string
	// assigning value
	str = "1041"
	// ParseInt() converts variable str to a integer number 
	// with the specified base and bitSize
	// diplays result
	fmt.Println(strconv.ParseInt(str, 10, 32))
	fmt.Println(strconv.ParseInt(str, 2, 64))
	fmt.Println()
	// reassigning value
	str = "-1041"
	// ParseFloat() converts variable str to a integer number 
	// with the specified base and bitSize
	// diplays result
	fmt.Println(strconv.ParseInt(str, 8, 32))
	fmt.Println(strconv.ParseInt(str, 16, 64))
	fmt.Println()

  	// reassigning value
	str = "1Shots12"
	// ParseInt() converts variable str to a integer number 
	// with the specified base and bitSize
	// diplays result
	fmt.Println(strconv.ParseInt(str, 2, 32))
	fmt.Println(strconv.ParseInt(str, 16, 64))
	fmt.Println()
	// reassigning value
	str = "00101110111111"
	// ParseFloat() converts variable str to a integer number 
	// with the specified base and bitSize
	// diplays result
	fmt.Println(strconv.ParseInt(str, 16, 32)) // throw out of range error
	fmt.Println(strconv.ParseInt(str, 16, 64))
	fmt.Println()
}

Explanation

  • Line 1: We add the main package.

  • Lines 3 to 6: We import necessary packages in Golang project.

  • Lines 11 to 21: We define the main() function, variable str of string type and assign a value to it, and then converts variable str to an integer number using the ParseInt() function with the specified base and bitSize. Finally, the result is displayed.

RELATED TAGS

golang
strconv
communitycreator
RELATED COURSES

View all Courses

Keep Exploring