解码字节数组:索引超出范围

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

Decoding bytes array: index out of range

问题

运行以下小程序来解码一个字符串:

  1. package main
  2. import (
  3. "fmt"
  4. "encoding/hex"
  5. )
  6. func main() {
  7. var answer []byte
  8. b, e := hex.Decode(answer, []byte("98eh1298e1h182he"))
  9. fmt.Println(b)
  10. fmt.Println(e)
  11. }

结果是 panic: runtime error: index out of range,尽管这不是一个非常有用的错误信息。我做错了什么?

对于编码也是一样的:

  1. package main
  2. import (
  3. "fmt"
  4. "encoding/hex"
  5. )
  6. func main() {
  7. var answer []byte
  8. e := hex.Encode(answer, []byte("98eh1298e1h182he"))
  9. fmt.Println(answer)
  10. fmt.Println(e)
  11. }

请问有什么问题吗?

英文:

Running the following little program to decode a string:

  1. package main
  2. import (
  3. "fmt"
  4. "encoding/hex"
  5. )
  6. func main()
  7. {
  8. var answer []byte
  9. b, e := hex.Decode(answer, []byte("98eh1298e1h182he"))
  10. fmt.Println(b)
  11. fmt.Println(e)
  12. }

Results in panic: runtime error: index out of range, though that is not a very helpful error message. What am I doing wrong?

The same is true for encoding:

  1. package main
  2. import (
  3. "fmt"
  4. "encoding/hex"
  5. )
  6. func main()
  7. {
  8. var answer []byte
  9. e := hex.Encode(answer, []byte("98eh1298e1h182he"))
  10. fmt.Println(answer)
  11. fmt.Println(e)
  12. }

答案1

得分: 3

hex.Encode将写入尚未分配的数组answer。虽然这段代码对我有效,但你可能会找到更优雅的方法来实现:

  1. package main
  2. import (
  3. "fmt"
  4. "encoding/hex"
  5. )
  6. func main() {
  7. var src []byte = []byte("98ef1298e1f182fe")
  8. answer := make([]byte, hex.DecodedLen(len(src)))
  9. b, e := hex.Decode(answer, src)
  10. fmt.Println(b)
  11. fmt.Println(e)
  12. fmt.Println(answer)
  13. }

运行结果:

  1. $ go build s.go && ./s
  2. 8
  3. <nil>
  4. [152 239 18 152 225 241 130 254]
英文:

hex.Encode is going to write into the array answer which isn't allocated yet. This worked for me, though you might find a more elegant way to do this:

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;encoding/hex&quot;
  5. )
  6. func main() {
  7. var src []byte = []byte(&quot;98ef1298e1f182fe&quot;)
  8. answer := make([]byte, hex.DecodedLen(len(src)))
  9. b, e := hex.Decode(answer, src)
  10. fmt.Println(b)
  11. fmt.Println(e)
  12. fmt.Println(answer)
  13. }

Running it:

  1. $ go build s.go &amp;&amp; ./s
  2. 8
  3. &lt;nil&gt;
  4. [152 239 18 152 225 241 130 254]

huangapple
  • 本文由 发表于 2013年8月11日 13:41:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/18169120.html
匿名

发表评论

匿名网友

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

确定