英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论