How to convert String to Int type in GoLang | GoLang Tutorial

5 years ago Lalit Bhagtani 0

In this tutorial, we will learn about how to convert string to int type in Go programming language.

ParseInt

The function ParseInt converts the string in the given base (0, 2 to 36) to a integer number with the precision specified by bitSize value passed as an argument. The bitSize value can be of four type, 0 for int, 8 for int8, 16 for int16, 32 for int32 and 64 for int64 data type, any value below 0 and above 64 results in an error.

If base value is 0, then base is implied by the string’s prefix, “ob” for base 2, “o” for base 8, “ox” for base 16 and if no prefix is given then base 10. Any base value which is 1, or below 0, or above 36 results in an error.

When string is empty or contains invalid digits, then syntax error (err.Err = ErrSyntax) is returned and the returned value is 0. If the value corresponding to string cannot be represented by a signed integer of the given size, then range error (err.Err = ErrRange) is returned and the returned value is the maximum magnitude integer that can be fit to the given bitSize.

Syntax

func ParseInt(str string, base int, bitSize int) (i int64, err error)

Example

package main

import (
    "fmt"
    "strconv"
)

func main() {

    var (
	numDecimal     string = "10"
	numHexaDecimal string = "0xabcd"
	numBinary      string = "0b1011"

	numHexaDec string = "abcd"
	numBin     string = "1011"
	numDec     string = "10S10"
    )

    first, _ := strconv.ParseInt(numDecimal, 0, 8)
    fmt.Printf("%T, %v\n", first, first)

    second, _ := strconv.ParseInt(numHexaDecimal, 0, 64)
    fmt.Printf("%T, %v\n", second, second)

    third, _ := strconv.ParseInt(numBinary, 0, 32)
    fmt.Printf("%T, %v\n", third, third)

    fourth, _ := strconv.ParseInt(numHexaDec, 16, 32)
    fmt.Printf("%T, %v\n", fourth, fourth)

    fifth, _ := strconv.ParseInt(numBin, 2, 32)
    fmt.Printf("%T, %v\n", fifth, fifth)

    sixth, error := strconv.ParseInt(numDec, 10, 64)
    fmt.Printf("%T, %v, %v\n", sixth, sixth, error)
}

Output

int64, 10
int64, 43981
int64, 11
int64, 43981
int64, 11
int64, 0, strconv.ParseInt: parsing "10S10": invalid syntax

References

  1. ParseInt function Docs

That’s all for how to convert string to int type in Go programming language. if you liked it, please share your thoughts in comments section and share it with others too.