使用多种方式转换十六进制值会得到不同的输出结果。

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

Converting hex value by using multiple ways results in different outputs

问题

将一个十六进制值使用两个不同的函数转换会得到略有不同的输出结果。例如:

b, _ := new(big.Int).SetString("00662ad25db00e7bb38bc04831ae48b4b446d12698", 16)
fmt.Println(b.Bytes())
// 输出 [102 42 210 93 176 14 123 179 139 192 72 49 174 72 180 180 70 209 38 152]

fmt.Println(hex.DecodeString("00662ad25db00e7bb38bc04831ae48b4b446d12698"))
// 输出 [0 102 42 210 93 176 14 123 179 139 192 72 49 174 72 180 180 70 209 38 152]

在 playground 上运行

为什么 DecodeString 的输出结果有一个前导的 0,而 big.Int 没有呢?

英文:

Converting an hex value with two different func result in slightly different output
For example

b, _ := new(big.Int).SetString("00662ad25db00e7bb38bc04831ae48b4b446d12698", 16)
fmt.Println(b.Bytes())
// output [102 42 210 93 176 14 123 179 139 192 72 49 174 72 180 180 70 209 38 152]

fmt.Println(hex.DecodeString("00662ad25db00e7bb38bc04831ae48b4b446d12698"))
// output [0 102 42 210 93 176 14 123 179 139 192 72 49 174 72 180 180 70 209 38 152]

Run it on the playground.

Why is DecodeString have a leading 0 and big.Int does not?

答案1

得分: 5

Int.SetString 方法将字符串解释为编码的数字。在数字编码中,前导零不重要。例如,十六进制数编码的 0001 和 1 都表示数字 1。

hex.DecodeString 函数将字符串解释为十六进制编码的字节。前导零字节是重要的。

英文:

The Int.SetString method interprets the string as an encoded number. Leading zeros are not significant in number encodings. For example, the hexadecimal number encodings 0001 and 1 both represent the number 1.

The hex.DecodeString function interprets the string as hexadecimal encoded bytes. The leading zero byte is significant.

答案2

得分: 2

如果你反向拆分输入,你会得到以下结果:

00 66 2a d2 5d b0 0e 7b b3 8b c0 48 31 ae 48 b4 b4 46 d1 26 98

所以你可以看到,最高有效位(MSB)[1]是零,所以在输出中是可选的,就像这个程序成功运行一样:

package main

func main() {
   println(01 == 1)
}
  1. https://wikipedia.org/wiki/Bit_numbering#Most_significant_byte
英文:

If you reverse split your input, you get this:

00 66 2a d2 5d b0 0e 7b b3 8b c0 48 31 ae 48 b4 b4 46 d1 26 98

So as you can see, the MSB [1] is zero, so it is optional in the output, similar to
how this program runs successfully:

package main

func main() {
   println(01 == 1)
}
  1. https://wikipedia.org/wiki/Bit_numbering#Most_significant_byte

huangapple
  • 本文由 发表于 2021年6月27日 09:48:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/68147382.html
匿名

发表评论

匿名网友

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

确定