Chris
Chris

Reputation: 12181

Decoding bytes array: index out of range

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

Upvotes: 2

Views: 1459

Answers (1)

Ray Toal
Ray Toal

Reputation: 88378

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

Running it:

$ go build s.go && ./s
8
<nil>
[152 239 18 152 225 241 130 254]

Upvotes: 3

Related Questions