2

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

1 回答 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]
于 2013-08-11T06:00:50.877 回答