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

时间:2013-08-11 05:41:21

标签: arrays go bytearray

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

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)
}

1 个答案:

答案 0 :(得分:2)

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]