2

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...

user1135541
  • 1,781
  • 3
  • 19
  • 41

1 Answers1

11

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

OneOfOne
  • 95,033
  • 20
  • 184
  • 185
  • Just to point out something about the 2nd approach, it wouldn't work on appengine and it will give you the wrong number on a bigendian cpu, but for uint64 it's so much faster it's not even funny. – OneOfOne Aug 20 '14 at 16:11
  • I thought unsafe was verboten on AppEngine, no? – David Budworth Aug 21 '14 at 00:00
  • @DavidBudworth unsafe doesn't work on gae as far as I know, unless they changed something recently. But you can always implement the function twice one "safe" and one unsafe for performance reasons. For example https://github.com/OneOfOne/xxhash/blob/master/native/xxhash_unsafe.go https://github.com/OneOfOne/xxhash/blob/master/native/xxhash_safe.go – OneOfOne Aug 21 '14 at 00:58