简体   繁体   English

int16到字节数组

[英]int16 to byte array

I'm trying to convert a int16 to a byte array but i cant seem to get it to work. 我正在尝试将int16转换为字节数组,但我似乎无法让它工作。
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. 此外,如果有人想知道数组需要长度为2。

While FUZxxl's answer works, you can also use the encoding/binary package: 虽然FUZxxl的答案有效,但您也可以使用编码/二进制包:

var i int16 = 41
b := make([]byte, 2)
binary.LittleEndian.PutUint16(b, uint16(i))

The encoding/binary package has prebuilt functions for encoding little and big endian for all fixed size integers and some easy to use functions if you are using Readers and Writers instead of byte slices. 编码/二进制包具有预编译函数,用于为所有固定大小的整数编码小端和大端,以及一些易于使用的函数,如果您使用读者和写入器而不是字节片。 Example: 例:

var i int16 = 41
err := binary.Write(w, binary.LittleEndian, i)

If you want to get the bytes of an int16, try something like this: 如果你想获得int16的字节,试试这样的事情:

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. Go尝试使编写依赖于平台属性的程序(如字节顺序)变得困难。 Thence, type punning that leads to such dependencies (such as overlaying a byte-array with an int16) is forbidden. 因此,禁止导致这种依赖性的类型惩罚(例如用int16覆盖字节数组)。

In case you really want to shoot yourself in the foot, try the package unsafe . 如果你真的想用脚射击自己,试试包不安全

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM