Index out of range [3] with length 2 while doing conversion of UInt

I have my codes here Go Playground - The Go Programming Language. What I have defined and ensure is the byte array of size length as 2. Everything works fine but when comes to this line speed2ComplimentUint := binary.BigEndian.Uint32(speed2ComplimentByte) I am getting this array panic: runtime error: index out of range [3] with length 2. I have limited the byte array to just 2 here speed2ComplimentByte := make([]byte, 2). But why it say range[3] ?

binary.BigEndian.Uint32 “reinterprets” a []byte as a 32-bit unsigned big endian integer. In doing so it will attempt to consume 32 bits from the array which is 4 bytes. Modifying your code to allocate 4 bytes of memory for the slice shows a succesful run:

Hi Jordan,
But wouldnt that cause my number to be very big when I allocate as 4 byte due to the additional byte ?

Hi Jordan,
Ok I got this idea is to fill the first 2 bytes as 0 permanently and only fill the rest with my values does this makes sense and correct ? Here is my latest codes Go Playground - The Go Programming Language

Changing which bytes you fill will work. You can also interpret at a uint16 which will only have 2 bytes.

uint32 is 4 bytes long. If you only want to use 2 bytes, then you must store a uint16 with bits.ByteOrder.Uint16 like @jordan-bonecutter suggested.

1 Like

Hi Guys,
Thank you yes I opted with your solution of uint16 and it works perfectly.