Convert String to Int in Golang

Convert string to int in golang

In the previous blog, we learned about how to convert from int to string in Golang. This time we are going to learn how we can convert a string (number as string) to int in Golang, so that we can perform numerical operations on it.

Learn int to string conversion from here.

Convert String to Int in Golang using strconv Atoi Function

func Atoi(s string) (int, error)

The Golang Strconv Atoi function takes a string value and retruns the integer value of the string and an error if that string value is not an integer value.

Example:

v := "10"
s, err := strconv.Atoi(v)
fmt.Printf("%T, %v\t", s, s)
fmt.Println(err)
v = "Golang"
s, err = strconv.Atoi(v)
fmt.Printf("%T, %v\t", s, s)
fmt.Println(err)

Output:

int, 10
int, 0 strconv.Atoi: parsing "Golang": invalid syntax

When an invalid integer string is passed it returns an error and the value retruned is zero.

Golang Strconv ParseInt

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

The ParseInt Function in go strconv package takes a string, the base value, and the bit size and returns an integer of int64 and an error.

Example:

var n int64
var err error

n, err = strconv.ParseInt("-3546343826724305832", 10, 32)
fmt.Printf("%T %v %v\n", n, n, err)

n, err = strconv.ParseInt("-354634382", 10, 32)
fmt.Printf("%T %v %v\n", n, n, err)

n, err = strconv.ParseInt("-3546343826724305832", 10, 64)
fmt.Printf("%T %v %v\n", n, n, err)
int64 -2147483648 strconv.ParseInt: parsing "-3546343826724305832": value out of range
int64 -354634382 <nil>
int64 -3546343826724305832 <nil>

If the base Argument is Zero (0), the string is prefixed with some values so that the go compiler can understand how to parse the values.

  • 0b‘ for Binary (Base 2)
  • 0‘ or ‘0o‘ for octal (Base 8)
  • 0x‘ for Hex (Base 16)

If the string is not prefixed the string will be treated as base 10 value.

var n int64
var err error

n, err = strconv.ParseInt("0b1001", 0, 8)
fmt.Printf("Binary %T %v %v\n", n, n, err)

n, err = strconv.ParseInt("0101", 0, 8)
fmt.Printf("Octal %T %v %v\n", n, n, err)

n, err = strconv.ParseInt("0o001", 0, 8)
fmt.Printf("Octal %T %v %v\n", n, n, err)

n, err = strconv.ParseInt("0x2a", 0, 8)
fmt.Printf("Hex %T %v %v\n", n, n, err)
Binary int64 9
Octal int64 65
Octal int64 65
Hex int64 42

Learn more about Golang strconv package from the official Documentation.

Tags: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *