Golang (also known as Go language) is an open source programming language developed and maintained by Google. Base conversion in Golang is a very basic operation. In this article, we will introduce how to use Golang for base conversion.
First, let’s look at how to convert decimal to other bases, such as binary, octal, and hexadecimal. In Golang, this task can be easily accomplished using the Printf() function of the fmt package. The following is a sample code that converts the decimal number 13 to binary, octal, and hexadecimal:
package main
import "fmt"
func main() {
n := 13 fmt.Printf("13的二进制表示为:%b\n", n) fmt.Printf("13的八进制表示为:%o\n", n) fmt.Printf("13的十六进制表示为:%x\n", n)
}
The output result is: The binary representation of
13 is: 1101 The octal representation of
13 is: 15
13’s hexadecimal representation Represented as: d
Next, let’s look at how to convert binary, octal, and hexadecimal to decimal. This can be achieved through the strconv package in Golang. This package provides many string-related functions, including functions for parsing integers in different bases. The following is an example code that converts the binary number 1101, the octal number 15, and the hexadecimal number d to decimal:
package main
import (
"fmt" "strconv"
)
func main() {
b := "1101" dec1, _ := strconv.ParseInt(b, 2, 64) fmt.Printf("%s的十进制表示为:%v\n", b, dec1) o := "15" dec2, _ := strconv.ParseInt(o, 8, 64) fmt.Printf("%s的十进制表示为:%v\n", o, dec2) h := "d" dec3, _ := strconv.ParseInt(h, 16, 64) fmt.Printf("%s的十进制表示为:%v\n", h, dec3)
}
The output result is: The decimal representation of
1101 is: 13The decimal representation of
15 is: The decimal representation of 13
d is: 13
In addition to conversion between decimal systems, Golang also provides How to convert between bases. The Itoa() function in the strconv package can convert an integer into a string, and the FormatInt() function can convert an integer into a string in a specific base. The following is a sample code that converts the hexadecimal number d to binary or octal:
package main
import (
"fmt" "strconv"
)
func main() {
h := "d" //将十六进制数d转换为二进制 dec, _ := strconv.ParseInt(h, 16, 64) fmt.Printf("%s的二进制表示为:%b\n", h, dec) //将十六进制数d转换为八进制 oct, _ := strconv.ParseInt(h, 16, 64) fmt.Printf("%s的八进制表示为:%o\n", h, oct)
}
The output result is: The binary representation of
d is: 1101 The octal representation of
d is: 15
Conclusion
Base conversion through Golang is a very basic operation. This article introduces the method of using the fmt package and strconv package to perform base conversion, including converting decimal to other bases, converting other bases to decimal, converting between bases, etc. I hope this article can help Golang beginners.
The above is the detailed content of A brief analysis of Golang's method of base conversion. For more information, please follow other related articles on the PHP Chinese website!