英文:
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 (
"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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论