在Go语言中使用位字符串和big.Int进行操作

huangapple go评论77阅读模式
英文:

Working with bitstrings and big.Int in Go

问题

我是你的中文翻译助手,以下是翻译好的内容:

我刚开始学习Go,并且正在进行一些练习以提高熟练度。在Go中,如何将表示一系列位的字符串转换为适当的数据类型?

例如,如果它是表示64位数字的位字符串,可以这样做:

val, err := strconv.ParseInt(bitstring, 2, 64)

然而,如果位字符串表示一个更大的数字(比如1024位或2048位),我该如何将该数字转换为Go中适当的类型?我相信在Go中管理大整数的类型是big.Int。

英文:

I'm new to Go and I'm working on a few exercises to get up to speed. How can I convert a string representing a sequence of bits to the appropriate datatype in Go?

For eg, I see that if its a bitstring representing a 64-bit number, I can do :-

val, err := strconv.ParseInt(bitstring, 2, 64)

However, if the bitstring represents a larger number(say 1024 or 2048 bits), how can I go about converting that number to the appropriate type in Go? I believe the type for managing big integers in Go is big.Int.

答案1

得分: 2

是的,你可以使用big.Int类型以及它的Int.SetString()方法,将2作为基数传入。

示例:

i := big.NewInt(0)
if _, ok := i.SetString("10101010101010101010101010101010101010101010101010101010101010101010101010", 2); !ok {
    fmt.Println("Invalid number!")
} else {
    fmt.Println(i)
}

输出结果(在Go playground上尝试):

12592977287652387236522
英文:

Yes, you may use the big.Int type, and its Int.SetString() method, passing 2 as the base.

Example:

i := big.NewInt(0)
if _, ok := i.SetString("10101010101010101010101010101010101010101010101010101010101010101010101010", 2); !ok {
	fmt.Println("Invalid number!")
} else {
	fmt.Println(i)
}

Output (try it on the Go playground):

12592977287652387236522

huangapple
  • 本文由 发表于 2017年7月9日 21:31:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/44996955.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定