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

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

Decoding bytes array: index out of range

问题

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

package main

import (
  "fmt"
  "encoding/hex"
)

func main() {
    var answer []byte
    b, e := hex.Decode(answer, []byte("98eh1298e1h182he"))
    fmt.Println(b)
    fmt.Println(e)
}

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

对于编码也是一样的:

package main

import (
  "fmt"
  "encoding/hex"
)

func main() {
    var answer []byte
    e := hex.Encode(answer, []byte("98eh1298e1h182he"))
    fmt.Println(answer)
    fmt.Println(e)
}

请问有什么问题吗?

英文:

Running the following little program to decode a string:

package main

import (
  "fmt"
  "encoding/hex"
)

func main()
{
  	var answer []byte
  	b, e := hex.Decode(answer, []byte("98eh1298e1h182he"))
	fmt.Println(b)
	fmt.Println(e)
}

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:

package main

import (
  "fmt"
  "encoding/hex"
)

func main()
{
  	var answer []byte
  	e := hex.Encode(answer, []byte("98eh1298e1h182he"))
	fmt.Println(answer)
	fmt.Println(e)
}

答案1

得分: 3

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

package main

import (
  "fmt"
  "encoding/hex"
)

func main() {
    var src []byte = []byte("98ef1298e1f182fe")
    answer := make([]byte, hex.DecodedLen(len(src)))
    b, e := hex.Decode(answer, src)
    fmt.Println(b)
    fmt.Println(e)
    fmt.Println(answer)
}

运行结果:

$ go build s.go && ./s
8
<nil>
[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:

package main

import (
  &quot;fmt&quot;
  &quot;encoding/hex&quot;
)

func main() {
    var src []byte = []byte(&quot;98ef1298e1f182fe&quot;)
    answer := make([]byte, hex.DecodedLen(len(src)))
    b, e := hex.Decode(answer, src)
    fmt.Println(b)
    fmt.Println(e)
    fmt.Println(answer)
}

Running it:

$ go build s.go &amp;&amp; ./s
8
&lt;nil&gt;
[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:

确定