Skip to content

How to Convert String to Integer in Go? (Golang String to Int)

How to Convert String to Integer in Go? (Golang String to Int)

In Go (Golang), converting a string to an integer is a common task, especially when working with user inputs or data from external sources. Go provides built-in functions to facilitate this conversion, making it straightforward. In this guide, we’ll explore how to convert strings to integers using the strconv package, which is part of Go’s standard library.

Converting String to Integer

Let’s explore some methods that we can use to convert data from string to integer type in Go.

Method 0: Implementation from Scratch

Before using built-in functions to convert strings to integers in Go, it’s important to try the operation yourself. It will increase your understanding of the conversion process and enhance your overall programming skills and concepts in Go.

package main

import (
	"errors"
	"fmt"
)

func stringToInt(s string) (int, error) {
	if s == "" {
		return 0, errors.New("empty string")
	}

	result := 0
	sign := 1
	startIndex := 0

	// Check for a negative sign
	if s[0] == '-' {
		sign = -1
		startIndex = 1
	} else if s[0] == '+' {
		startIndex = 1
	}

	// Convert each character to its integer value
	for i := startIndex; i < len(s); i++ {
		digit := int(s[i] - '0') // Convert char to int

		// Check for valid digit
		if digit < 0 || digit > 9 {
			return 0, errors.New("invalid character in string")
		}

		result = result*10 + digit
	}

	return result * sign, nil
}

Explanation

Let’s look at a detailed explanation of this code to better understand the process of conversion.

  • Function Definition: The stringToInt function takes a string as input and returns an integer and an error.
  • Empty String Check: It first checks if the string is empty and returns an error if it is.
  • Sign Handling: It checks for a negative (-) or positive (+) sign at the beginning of the string. The sign is stored, and the starting index for conversion is adjusted accordingly.
  • Character Conversion: The function iterates over each character, and converts it to its integer value by subtracting the ASCII value of '0', and constructs the final integer.
  • Error Handling: If an invalid character (non-digit) is encountered, it returns an error.

Example

The example demonstrates a dry run of the code.

Suppose you have the string "123" and you want to convert the character '2' to its integer value.

  1. Character to Convert: '2'
  2. ASCII Value of ‘2’: The ASCII value of the character '2' is 50.
  3. ASCII Value of ‘0’: The ASCII value of the character '0' is 48.
  4. Conversion: To get the integer value of the character '2', you subtract the ASCII value of '0' from the ASCII value of '2'. Integer Value = ASCII(′2′) − ASCII(′0′) = 50 − 48 = 2

This process effectively translates the character representation of a digit to its corresponding integer value. You can apply this same method to each character in the string to construct the full integer. For example, when iterating over the string "123":

  • For '1': 49 − 48 = 1
  • For '2': 50 − 48 = 2
  • For '3': 51 − 48 = 3

Finally, these values are combined to form the integer 123.

Method 1: Using strconv.Atoi()

Go’s strconv package provides functions to convert strings to various numeric types, including integers. We will use the strconv.Atoi() function which stands for “ASCII to integer” for converting strings to integers.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := "12345" // String to be converted
    num, err := strconv.Atoi(str) // Convert string to integer

    if err != nil {
        fmt.Println("Error converting string to integer:", err)
        return
    }

    fmt.Println("The converted integer is:", num) // Output: 12345
}

When converting strings to integers, it’s important to handle potential errors. The Atoi() function returns an error if the string is not a valid representation of an integer. For example, trying to convert "abc" would result in an error.

Here’s how to handle such errors:

str := "abc"
num, err := strconv.Atoi(str)
if err != nil {
    fmt.Println("Error:", err) // Output: Error: invalid syntax
} else {
    fmt.Println("The converted integer is:", num)
}
How to Convert String to Integer in Go? - Atoi()

Method 2: Using strconv.ParseInt()

If you need to convert a string representation of an integer in a specific base (e.g., binary, octal, hexadecimal), you can use strconv.ParseInt(). This function allows you to specify the base of the input string.

Syntax

The function call can be made using the following syntax format:

func ParseInt(s string, base int, bitSize int) (i int64, err error)
  1. s (string): The string to be converted to an integer.
  2. base (int): The numerical base for the conversion. This can be:
    • 0: Base is inferred from the string (e.g., 0x for hex, 0 for octal, or decimal).
    • 2 to 36: Specifies the base directly (e.g., 10 for decimal).
  3. bitSize (int): The bit size of the resulting integer. It can be:
    • 0: Uses the default size (usually 0-64 depending on the platform).
    • 8, 16, 32, or 64: Specifies the exact bit size.

The function returns an int64 value representing the parsed integer. The error will be nil if the conversion was successful otherwise it will contain information about the failure.

We can understand it better by an example. Let’s convert a hexadecimal string to an integer:

str := "1a"
num, err := strconv.ParseInt(str, 16, 0) // Base 16 for hexadecimal

if err != nil {
    fmt.Println("Error converting hexadecimal to integer:", err)
} else {
    fmt.Println("The converted integer is:", num) // Output: 26
How to Convert String to Integer in Go? - ParseInt()

Use Cases

  1. User Input: When reading user input, data is typically received as strings. If you need to perform numerical calculations, you’ll need to convert these strings to integers.
  2. Data Processing: When working with data from files, APIs, or databases, numeric values may be represented as strings. Converting them allows you to manipulate them mathematically.
  3. Type Safety: Go is a statically typed language, meaning types are enforced at compile time. This enforcement reduces the likelihood of runtime errors, such as attempting arithmetic operations on incompatible types. As a type-safe language, Go can catch type-related errors at compile time, allowing developers to identify issues early in the development process.

Conclusion

In Go, converting string to integer is a common task that can be done using a couple of methods. We discussed implementing the conversion from scratch and utilizing two built-in functions in the strconv package: Atoi(), and ParseInt():

  • Implementing from scratch allows for a deeper understanding of string-to-integer conversion. The code we discussed handles empty strings and invalid characters with error checks.
  • Using strconv.Atoi() converts a string to an integer by automatically inferring base 10. It includes error handling for invalid inputs.
  • Using strconv.ParseInt() supports conversion from a string in a specified base (e.g., binary, octal, hexadecimal). It allows the specification of bit size for the resulting integer and returns an int64 value. It also includes error handling for invalid inputs.

In addition to mastering string to integer conversion, it’s worth noting that Go is a vital language in blockchain development. Check out our article What programming languages are used for blockchain development? to learn more about its significance and capabilities in this evolving field.

FAQs

How does strconv.ParseInt() differ from strconv.Atoi()?

strconv.ParseInt() allows you to specify the base (from 2 to 36) and bit size for the converted value, making it suitable for various numerical systems, whereas strconv.Atoi() is simpler and specifically for base 10.

Can I convert negative numbers using these methods?

Yes, both strconv.Atoi() and strconv.ParseInt() support negative numbers if the string begins with a ‘-‘ sign. Custom implementations also need to handle this explicitly.

What happens if I pass an empty string to these conversion functions?

Passing an empty string will result in an error. In strconv.Atoi() and strconv.ParseInt(), the error message will indicate that the input is invalid.