Go - convert 2 byte array to uint16 value

If I have a piece of bytes in Go, then similarly this:

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

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

+4
source share
3 answers

you can use binary.BigEndian.Uint16(numBytes)
as this working example code (with comments):

package main

import (
    "encoding/binary"
    "fmt"
)

func main() {
    numBytes := []byte{0xFF, 0x10}
    u := binary.BigEndian.Uint16(numBytes)
    fmt.Printf("%#X %[1]v\n", 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
}

Hope this helps.

+6
source

Merge two bytes in uint16

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

where iis the starting position of uint16. So if your array always consists of only two elements, this will bex := uint16(numBytes[0])<<8 | uint16(numBytes[1])

+4
source

-, , - [2]byte.

2- , ,

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

: , uint16 - int , !

+1
source

Source: https://habr.com/ru/post/1649632/


All Articles