How to Convert String to Int64 in Go

Jay Singh Feb 02, 2024
How to Convert String to Int64 in Go

An int is generally used for an index, length, or capacity. The int type is always large enough to handle an array’s maximum length.

The data types int8, int16, int32, and int64 (as well as their unsigned cousins) are the finest. When memory isn’t an issue, an int64 is the most common choice.

In this post, we’ll convert a string to an int64.

Convert String to Int64 Using the Parselnt() in Go

strconv.ParseInt() is a built-in function in Go that parses a decimal string (base 10) and checks if it fits in an int64. The implementation determines the size of an int; it might be 32 or 64 bits, which is why switching from int to int64 causes no data loss.

In this example, strconv.ParseInt() is used to convert a decimal string (base 10) to a 64-bit signed integer and confirm that it fits.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	str := "10101101"
	n, err := strconv.ParseInt(str, 10, 64)
	if err == nil {
		fmt.Printf("%d is type %T", n, n)
	}
}

Output:

10101101 is type int64

Moreover, ParseInt translates a string and returns the appropriate value in the provided base (0, 2 to 36) and bit size (0 to 64). This method takes a string parameter and, using a base parameter, converts it to an int type.

It returns an Int64 value by default.

package main

import (
	"fmt"
	"reflect"
	"strconv"
)

func main() {
	strVar := "110"

	intVar, err := strconv.ParseInt(strVar, 0, 8)
	fmt.Println(intVar, err, reflect.TypeOf(intVar))

	intVar, err = strconv.ParseInt(strVar, 0, 16)
	fmt.Println(intVar, err, reflect.TypeOf(intVar))

	intVar, err = strconv.ParseInt(strVar, 0, 32)
	fmt.Println(intVar, err, reflect.TypeOf(intVar))

	intVar, err = strconv.ParseInt(strVar, 0, 64)
	fmt.Println(intVar, err, reflect.TypeOf(intVar))
}

Output:

110 <nil> int64
110 <nil> int64
110 <nil> int64
110 <nil> int64

Related Article - Go String