将字节数组的一部分隐蔽到uint16的最简单方法 [英] Easiest way to covert part of a byte array to uint16

查看:41
本文介绍了将字节数组的一部分隐蔽到uint16的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我是字节数组:

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

我想以LittleEndian顺序将字节\ x15和\ xf1传递到uint16.最简单的方法是什么?

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

尝试了以下内容:

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?

谢谢...

推荐答案

您有2个选项,使用binary.LittleEndian,就像您已经做过的一样,一种较短的方法是:

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

游乐场

这篇关于将字节数组的一部分隐蔽到uint16的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆