Use the strconv.ParseInt function to convert a string into an integer in a specified base number
Although the strconv package in the Go language provides many functions for type conversion, sometimes we still need custom types Convert. When we need to convert a string into an integer in a specified base, we can use the strconv.ParseInt function to complete it.
The parameters of the strconv.ParseInt function include the string to be converted, the specified base and the number of digits in the result integer. It returns the converted integer value and an error value.
Let's look at an example below. Suppose we want to convert the hexadecimal string "1A" to a decimal integer. The code example is as follows:
package main import ( "fmt" "strconv" ) func main() { hexString := "1A" base := 16 bitSize := 64 decimalInt, err := strconv.ParseInt(hexString, base, bitSize) if err != nil { fmt.Println("转换出错:", err) return } fmt.Printf("十六进制字符串%s转换为十进制整数为%d ", hexString, decimalInt) }
In the above code, we first define the hexadecimal string to be converted as "1A", specify the base as 16, and the resulting integer is 64 bits. Then use strconv.ParseInt function to convert. If a conversion error occurs, the program will print an error message and exit; if the conversion is successful, the program will print the converted decimal integer.
When we run the above code, the output result is:
十六进制字符串1A转换为十进制整数为26
As you can see, the string "1A" is successfully converted to the decimal integer 26.
In addition to hexadecimal, we can also convert strings in other bases into decimal integers. Just set the base parameter to the corresponding base. Here is an example of converting a binary string to a decimal integer:
binaryString := "1010" base := 2 bitSize := 64 decimalInt, err := strconv.ParseInt(binaryString, base, bitSize)
Similarly, we can convert octal and decimal strings to decimal integers. Just set the base parameters to 8 and 10 respectively.
It should be noted that when the string to be converted contains invalid characters, the program will return an error. It is important to check for errors and handle them appropriately.
By using the strconv.ParseInt function, we can easily convert a string into an integer in a specified base. This makes us more flexible and convenient when processing data.
The above is the detailed content of Use the strconv.ParseInt function to convert a string into an integer in the specified base. For more information, please follow other related articles on the PHP Chinese website!