user1135541
user1135541

Reputation: 1891

Easiest way to covert part of a byte array to uint16

if I byte array:

byte_array := []byte("klm,\x15\xf1\n")

I would like to the byte \x15 and \xf1 to uint16 in LittleEndian order. What is the easiest way of doing it?

Tried the following:

var new_uint uint16
bff := bytes.newRead(byte_array[4:5])
err = binary.Read(buff, binary.LittleEndian, &new_uint)

but I keep getting nothing, and this is relatively complicated, is there an easier way of doing it?

Thanks...

Upvotes: 2

Views: 3570

Answers (1)

OneOfOne
OneOfOne

Reputation: 99254

You have 2 options, using binary.LittleEndian like you already did, a shorter way is:

u16 := binary.LittleEndian.Uint16(byte_array[4:])

Or if you like to live dangerously, you can use unsafe:

// This will return the wrong number on a BE system,
// also unsafe is not available on GAE.
u16 := *(*uint16)(unsafe.Pointer(&byte_array[4]))

playground

Upvotes: 11

Related Questions