Go-将2字节数组转换为uint16值

If I have a slice of bytes in Go, similar to this:

numBytes := []byte { 0xFF, 0x10 }

How would I convert it to it's uint16 value (0xFF10, 65296)?

you may use binary.BigEndian.Uint16(numBytes)
like this working sample code (with commented output):

package main

import (
    "encoding/binary"
    "fmt"
)

func main() {
    numBytes := []byte{0xFF, 0x10}
    u := binary.BigEndian.Uint16(numBytes)
    fmt.Printf("%#X %[1]v
", u) // 0XFF10 65296
}

and see inside binary.BigEndian.Uint16(b []byte):

func (bigEndian) Uint16(b []byte) uint16 {
    _ = b[1] // bounds check hint to compiler; see golang.org/issue/14808
    return uint16(b[1]) | uint16(b[0])<<8
}

I hope this helps.

To combine two bytes into uint16

x := uint16(numBytes[i])<<8 | uint16(numBytes[i+1])

where i is the starting position of the uint16. So if your array is always only two items it would be x := uint16(numBytes[0])<<8 | uint16(numBytes[1])

Firstly you have a slice not an array - an array has a fixed size and would be declared like this [2]byte.

If you just have a 2 bytes slice, I wouldn't do anything fancy, I'd just do

numBytes := []byte{0xFF, 0x10}
n := int(numBytes[0])<<8 + int(numBytes[1])
fmt.Printf("n =0x%04X = %d
", n, n)

Playground

EDIT: Just noticed you wanted uint16 - replace int with that in the above!