String to int conversion in Golang
In Golang, converting strings to integers is crucial. Golang offers specific methods for this task. This blog focuses on string to integer conversion in Golang, exploring strconv.Atoi, strconv.ParseInt and fmt.Sscan. Understanding these methods’ strengths will improve your code’s performance and reliability.
Using strconv.Atoi() function
Function syntax : Atoi(s string) (int, error)
Purpose : The strconv package in Golang provides the function Atoi() for converting strings to integer.
Parameter
- s string: The input string to be converted to an integer.
Return values
- int: The parsed integer value.
- error: An error value indicating whether the conversion was successful. If the conversion fails, error will be non-nil.
Let’s understand the function’s usage with the following example:
package main
import (
"fmt"
"strconv"
)
func main() {
str := "12345"
num, err := strconv.Atoi(str)
if err != nil {
fmt.Println("Error converting string to int:", err)
return
}
fmt.Printf("%T, %v\n", num, num)
}
//Output : int, 1234567
Explanation
string to Integer Conversion:
- str := “12345“: Initializes a string variable str with the value “12345”.
- num, err := strconv.Atoi(str): Converts the string str to an integer using strconv.Atoi.
- strconv.Atoi returns two values: the converted integer num and an error err.
- If the conversion is successful, err will be nil, and num will hold the converted integer value.
- If there’s an error during conversion (e.g., if str is not a valid integer string), err will contain information about the error.
Using strconv.ParseInt() function
Function Syntax:
ParseInt (s string, base int, bitSize int) (int64, error)
Purpose: The strconv package in the Golang provides a function ParseInt for converting string to int64.
Parameters:
- s string: The input string to be converted to an integer(i.e. int64).
- base int: The base of the number in the int. It can be 2 (binary), 8 (octal), 10 (decimal), or 16 (hexadecimal). If base is 0, the function infers the base from the string prefix.
- If there is no prefix, it defaults to base 10.
- bitSize int: This parameter specifies the maximum size of the integer type that the parsed value should fit into.
It can be:
- 0: This means the default integer type, which is typically int in Go.
- 8: This means the parsed value should fit within an 8-bit integer (which corresponds to int8).
- 16: This means the parsed value should fit within a 16-bit integer (which corresponds to int16).
- 32: This means the parsed value should fit within a 32-bit integer (which corresponds to int32).
- 64: This means the parsed value should fit within a 64-bit integer (which corresponds to int64).
Even though the function always returns an int64, the bitSize parameter ensures that the value fits within the specified size, and it will throw an error if the value is too large for the specified bit size.
Return Values:
- int64: The parsed integer value.
- error: An error value indicating whether the conversion was successful. If the conversion fails, err will be non-nil.
Let’s understand the function’s usage with the following example:
package main
import (
"fmt"
"strconv"
)
func main() {
str := "1000"
number, err := strconv.ParseInt(str, 2, 8)
fmt.Printf("%T \t%v \t%v \n", number, number, err)
number, err = strconv.ParseInt(str, 8, 16)
fmt.Printf("%T \t%v \t%v \n", number, number, err)
number, err = strconv.ParseInt(str, 16, 32)
fmt.Printf("%T \t%v \t%v \n", number, number, err)
number, err = strconv.ParseInt(str, 10, 64)
fmt.Printf("%T \t%v \t%v \n", number, number, err)
number, err = strconv.ParseInt(str, 0, 64)
fmt.Printf("%T \t%v \t%v \n", number, number, err)
}
//Output:
//int64 8 <nil>
//int64 512 <nil>
//int64 4096 <nil>
//int64 1000 <nil>
//int64 1000 <nil>
Detailed Explanation
number, err := strconv.ParseInt(str, 2, 8)
fmt.Printf("%T %v %v \n", number, number, err)
- str is “1000”, and it is being interpreted as a binary (base 2) number.
- The bitSize is set to 8, meaning it will check if the parsed value fits within the range of an int8 (-128 to 127).
- The binary “1000” is 8 in decimal, which fits within the int8 range.
- Output: int64 8 <nil>
number, err := strconv.ParseInt(str, 8, 16)
fmt.Printf("%T %v %v \n", number, number, err)
- str is “1000”, and it is being interpreted as an octal (base 8) number.
- The bitSize is set to 16, meaning it will check if the parsed value fits within the range of an int16 (-32768 to 32767).
- The octal “1000” is 512 in decimal, which fits within the int16 range.
- Output: int64 512 <nil>
number, err := strconv.ParseInt(str, 16, 32)
fmt.Printf("%T %v %v \n", number, number, err)
- str is “1000”, and it is being interpreted as a hexadecimal (base 16) number.
- The bitSize is set to 32, meaning it will check if the parsed value fits within the range of an int32 (-2147483648 to 2147483647).
- The hexadecimal “1000” is 4096 in decimal, which fits within the int32 range.
- Output: int64 4096 <nil>
number, err := strconv.ParseInt(str, 10, 64)
fmt.Printf("%T %v %v \n", number, number, err)
- str is “1000”, and it is being interpreted as a decimal (base 10) number.
- The bitSize is set to 64, meaning it will check if the parsed value fits within the range of an int64 (-9223372036854775808 to 9223372036854775807).
- The decimal “1000” is 1000, which fits within the int64 range.
- Output: int64 1000 <nill>
number, err := strconv.ParseInt(str, 0, 64)
fmt.Printf("%T %v %v \n", number, number, err)
- str is “1000”, and since the base is 0, the function infers the base from the string prefix.
- If there is no prefix, it defaults to base 10.
- The bitSize is set to 64, meaning it will check if the parsed value fits within the range of an int64.
- The decimal “1000” is 1000, which fits within the int64 range.
- Output: int64 1000 <nill>
In all cases, strconv.ParseInt returns an int64 value. The bitSize parameter only affects range and overflow checks, ensuring the parsed value fits within the specified bit size. The actual type of the returned value remains int64 for consistency.
To convert int64 to int, please refer Golang Type Casting or Conversion – Detailed Guide
Using fmt.Sscan
Function Syntax: fmt.Sscan (s string, a …interface{}) (int, error)
Purpose:
The fmt package in Golang provides a Sscan function for converting string to int, floating point number and bool.
Parameters:
- s string: The input string to be scanned.
- a …interface{}: The variables where the scanned values will be stored. Each variable should be a pointer.
Return Values:
- int: Represents the number of successfully scanned and assigned arguments. e.g. If the function successfully scans three values, n will be 3.
- error: An error value that will be nil if the scan is successful. If an error occurs (e.g., the input string cannot be parsed into the specified types), err will contain the error details.
package main
import (
"fmt"
)
func main() {
str := "31082024 3.14 true Golang"
var num int
var floatNum float64
var flag bool
var text string
n, err := fmt.Sscan(str, &num, &floatNum, &flag, &text)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Number of items scanned:", n)
fmt.Println("Parsed values:", num, floatNum, flag, text)
}
//Output :
//Number of items scanned: 4
//Parsed values: 31082024 3.14 true Golang
Explanation :
Input String:
- str := “31082024 3.14 true Golang”: Defines a string variable str that contains space-separated values.
Variable Declarations:
- var num int: Declares an integer variable num to store the first parsed value.
- var floatNum float64: Declares a floating-point variable floatNum to store the second parsed value.
- var flag bool: Declares a boolean variable flag to store the third parsed value.
- var text string: Declares a string variable text to store the fourth parsed value.
Parsing the String:
- n, err := fmt.Sscan(str, &num, &floatNum, &flag, &text): Uses the fmt.Sscan function to parse the space-separated values from str and store them in the respective variables.
- &num: Pointer to the integer variable num.
- &floatNum: Pointer to the floating-point variable floatNum.
- &flag: Pointer to the boolean variable flag.
- &text: Pointer to the string variable text.
- The fmt.Sscan function scans the input string and attempts to parse it into the provided pointers. It returns two values:
- n: The number of successfully scanned items.
- err: An error if one occurred during scanning.
Summary
- strconv.Atoi : This function is best for simple and efficient base-10 string to integer conversions.
- strconv.ParseInt : This function offers more flexibility by allowing you to specify the numeric base and bit size for the integer.Efficient for various bases and bit sizes but slightly less than Atoi.
- fmt.Sscan :
This function is useful for extracting multiple, space-separated values of different types from a single string.Least efficient for single integer conversions but highly versatile for parsing multiple values of different types.