how Convert 0xffffffff to -1 in go

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

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)

https://go.dev/play/p/l9WJ_KwsYu-

huangapple
  • 本文由 发表于 2022年3月17日 19:13:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/71511355.html
匿名

发表评论

匿名网友

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

确定