Golang 如何获取指定基数的字符串
Go语言通过strconv包提供内置支持,以实现基本数据类型的字符串表示形式与之间的转换。这个包提供了一个 FormatInt()函数 ,它用于返回x在给定基数下的字符串表示形式,即,2 <= base <= 36。
在这里,结果使用小写字母“a”到“z”作为大于等于10的数字值的位数。要访问FormatInt()函数,您需要使用import关键字在您的程序中导入strconv包。
语法:
func FormatInt(x int64, base int) string
参数: 此函数需要两个参数,即x和base。
返回值: 此函数返回x在给定基数下的字符串表示形式,即,2 <= base <= 36。
让我们通过给定的示例来讨论这个概念:
示例1:
// Golang程序来说明
// strconv.FormatInt()函数
package main
import (
"fmt"
"strconv"
)
func main() {
// 找到给定值在给定基数下的字符串表示形式
// 使用FormatInt()函数
fmt.Println(strconv.FormatInt(23, 2))
fmt.Println(strconv.FormatInt(-24, 10))
}
输出:
10111
-24
示例2:
// Golang程序来说明
// strconv.FormatInt()函数
package main
import (
"fmt"
"strconv"
)
func main() {
// 找到给定值在给定基数下的字符串表示形式
// 使用FormatInt()函数
val1 := int64(25)
res1 := strconv.FormatInt(val1, 2)
fmt.Printf("Result 1: %v", res1)
fmt.Printf("\nType 1: %T", res1)
val2 := int64(-50)
res2 := strconv.FormatInt(val2, 16)
fmt.Printf("\nResult 2: %v", res2)
fmt.Printf("\nType 2: %T", res2)
}
输出:
Result 1: 11001
Type 1: string
Result 2: -32
Type 2: string
极客教程