int16转换为字节数组 [英] int16 to byte array

查看:1503
本文介绍了int16转换为字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个int16转换为一个字节数组,但我似乎无法使它工作。

这是我现在所拥有的:

  int16 i:= 41 
a:= [] byte(string(i))// this line is wrong

另外如果有人想知道数组需要长度为2。 >解决方案

如果你想得到一个int16的字节,试试这样:

  var i int16 = 41 
var h,l uint8 = uint8(i>> 8),uint8(i& 0xff)



Go尝试使编写依赖于平台属性(例如字节顺序)的程序变得困难。因此,禁止导致这种依赖的类型双引号(例如用int16覆盖字节数组)。


如果您真的想在脚下自拍,请试用不安全的软件包


I'm trying to convert a int16 to a byte array but i cant seem to get it to work.
Here is what i've got right now:

int16 i := 41
a := []byte(string(i))//this line is wrong

Also if someone wonder the array needs to be a length of 2.

解决方案

If you want to get the bytes of an int16, try something like this:

var i int16 = 41
var h, l uint8 = uint8(i>>8), uint8(i&0xff)

Go tries to make it difficult to write programs that depend on attributes of your platform such as byte order. Thence, type punning that leads to such dependencies (such as overlaying a byte-array with an int16) is forbidden.

In case you really want to shoot yourself in the foot, try the package unsafe.

这篇关于int16转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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