Easiest way to covert part of a byte array to uint16

huangapple go评论77阅读模式
英文:

Easiest way to covert part of a byte array to uint16

问题

如果我有一个字节数组:

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

我想将字节\x15和\xf1以LittleEndian顺序转换为uint16。最简单的方法是什么?

我尝试了以下代码:

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

但是我一直得不到结果,而且这个方法相对复杂,有没有更简单的方法?

谢谢...

英文:

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

答案1

得分: 11

你有两个选择,使用像你已经做的那样的binary.LittleEndian,一个更简短的方法是:

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

或者如果你喜欢冒险,你可以使用unsafe:

// 这将在BE系统上返回错误的数字,
// 并且unsafe在GAE上不可用。
u16 := *(*uint16)(unsafe.Pointer(&byte_array[4]))

[kbd]playground[/kbd]

英文:

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]))

<kbd>playground</kbd>

huangapple
  • 本文由 发表于 2014年8月20日 23:39:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/25408954.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定