英文:
how Convert 0xffffffff to -1 in go
问题
我有以下字符串,我想将其转换为带括号的负数,有人可以告诉我如何在golang中实现吗?
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff -> (-1)
0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe -> (-2)
我知道有一些类似的答案在这里,但这不是我想要的。
英文:
I have the following string, I want to convert it to a negative number in parentheses, can someone tell me how to do it in golang?
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff -> (-1)
0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe -> (-2)
I know there are some similar looking answers here, but this is not what I want.
答案1
得分: 3
根据你提供的链接中的答案,你可以按照以下方式进行操作:
func main() {
slice := []string{
"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe",
}
for _, s := range slice {
s = strings.TrimPrefix(s, "0x")
i := &big.Int{}
i, _ = i.SetString(s, 16)
s = fmt.Sprintf("(%d)", i.Int64())
fmt.Println(s)
}
}
// 输出结果:
// (-1)
// (-2)
你可以在这里查看代码运行结果:https://go.dev/play/p/l9WJ_KwsYu-
英文:
Based on the answer that you've linked you can do the following:
func main() {
slice := []string{
"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe",
}
for _, s := range slice {
s = strings.TrimPrefix(s, "0x")
i := &big.Int{}
i, _ = i.SetString(s, 16)
s = fmt.Sprintf("(%d)", i.Int64())
fmt.Println(s)
}
}
// outputs:
// (-1)
// (-2)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论