从整数转换为其二进制表示 [英] Converting from an integer to its binary representation
问题描述
有没有人知道 Go 中是否有任何内置功能可以将任何一种数字类型转换为其二进制数形式.
Has anyone got an idea if there is any inbuilt functionality in Go for converting from any one of the numeric types to its binary number form.
例如,如果 123
是输入,则字符串 "1111011"
将是输出.
For example, if 123
was the input, the string "1111011"
would be the output.
推荐答案
strconv
包有 FormatInt
,它接受 int64
并让你指定基数.
The strconv
package has FormatInt
, which accepts an int64
and lets you specify the base.
n := int64(123)
fmt.Println(strconv.FormatInt(n, 2)) // 1111011
演示: http://play.golang.org/p/leGVAELMhv
http://golang.org/pkg/strconv/#FormatInt
func FormatInt(i int64, base int) 字符串
FormatInt 返回 i 在给定基数中的字符串表示形式,对于 2 <= base <= 36.对于 >= 10 的数字值,结果使用小写字母 'a' 到 'z'.
FormatInt returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' for digit values >= 10.
这篇关于从整数转换为其二进制表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!