📜  Golang中如何获取指定base中的字符串?

📅  最后修改于: 2021-10-25 02:47:12             🧑  作者: Mango

Go 语言提供内置支持,以通过strconv Package实现基本数据类型的字符串表示的转换。这个包提供了一个FormatInt()函数,用于返回给定基数中 x 的字符串表示,即 2 <= base <= 36。
在这里,结果使用小写字母 ‘a’ 到 ‘z’ 表示大于等于 10 的数字值。要访问 FormatInt()函数,您需要借助 import 关键字在程序中导入 strconv Package。

句法:

func FormatInt(x int64, base int) string

参数:该函数有两个参数,即x 和base。

返回值:该函数返回给定基数中 x 的字符串表示,即 2 <= base <= 36。

让我们在给定示例的帮助下讨论这个概念:

示例 1:

// Golang program to illustrate
// strconv.FormatInt() Function
package main
  
import (
    "fmt"
    "strconv"
)
  
func main() {
    // Finding the string representation
    // of given value in the given base
    // Using FormatInt() function
    fmt.Println(strconv.FormatInt(23, 2))
    fmt.Println(strconv.FormatInt(-24, 10))
  
}

输出:

10111
-24

示例 2:

// Golang program to illustrate
// strconv.FormatInt() Function
package main
  
import (
    "fmt"
    "strconv"
)
  
func main() {
  
    // Finding the string representation
    // of given value in the given base
    // Using FormatInt() function
    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