Golang中UInt转换时遇到索引越界错误:[3]超出长度2
Golang中UInt转换时遇到索引越界错误:[3]超出长度2
我的代码在Go Playground - Go 编程语言。我定义并确保字节数组的大小长度为2。一切运行正常,但执行到这一行 speed2ComplimentUint := binary.BigEndian.Uint32(speed2ComplimentByte) 时,我遇到了这个数组恐慌:运行时错误:索引超出范围 [3],长度为2。我在这里将字节数组限制为仅2个字节 speed2ComplimentByte := make([]byte, 2)。但为什么它说范围[3]?
更多关于Golang中UInt转换时遇到索引越界错误:[3]超出长度2的实战教程也可以访问 https://www.itying.com/category-94-b0.html
更改要填充的字节是可行的。你也可以将其解释为 uint16,它只占用2个字节。
func main() {
fmt.Println("hello world")
}
好的,乔丹, 我明白了,这个想法是永久地将前两个字节填充为0,只将剩余部分用我的值填充。这样做有意义且正确吗?以下是我最新的代码:Go Playground - The Go Programming Language
但这不会导致我的数字在分配为4字节时因为额外的字节而变得非常大吗?
uint32 的长度是4字节。如果你只想使用2字节,那么你必须像 @jordan-bonecutter 建议的那样,使用 bits.ByteOrder.Uint16 来存储一个 uint16。
这个错误是因为 binary.BigEndian.Uint32() 需要至少4个字节的切片,但你只提供了2个字节。函数内部会尝试访问索引0-3的字节,当访问索引3时就会超出你长度为2的切片边界。
示例代码演示:
package main
import (
"encoding/binary"
"fmt"
)
func main() {
// 错误示例 - 会导致panic
speed2ComplimentByte := make([]byte, 2)
// 这会panic: runtime error: index out of range [3] with length 2
// speed2ComplimentUint := binary.BigEndian.Uint32(speed2ComplimentByte)
// 正确做法1: 使用合适的函数处理2字节
speed2ComplimentByte = []byte{0x12, 0x34}
speed2ComplimentUint16 := binary.BigEndian.Uint16(speed2ComplimentByte)
fmt.Printf("Uint16: %d (0x%04x)\n", speed2ComplimentUint16, speed2ComplimentUint16)
// 正确做法2: 如果需要Uint32,确保有4个字节
speed4Bytes := make([]byte, 4)
copy(speed4Bytes[2:], speed2ComplimentByte) // 将2字节放到高16位
speed2ComplimentUint32 := binary.BigEndian.Uint32(speed4Bytes)
fmt.Printf("Uint32: %d (0x%08x)\n", speed2ComplimentUint32, speed2ComplimentUint32)
// 正确做法3: 直接使用4字节切片
fullBytes := []byte{0x00, 0x00, 0x12, 0x34}
result := binary.BigEndian.Uint32(fullBytes)
fmt.Printf("Direct Uint32: %d (0x%08x)\n", result, result)
}
根据你的需求选择:
- 如果原始数据是16位,使用
binary.BigEndian.Uint16() - 如果需要32位值,确保切片长度为4字节
- 可以使用
append()或手动填充来扩展字节切片到4字节



