英文:
int16 to byte array
问题
我试图将int16转换为字节数组,但似乎无法使其工作。这是我现在的代码:
int16 i := 41
a := []byte(string(i))//这行代码是错误的
另外,如果有人想知道,数组的长度需要为2。
英文:
I'm trying to convert a int16 to a byte array but i cant seem to get it to work.<br />
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.
答案1
得分: 53
虽然FUZxxl的答案是可行的,但你也可以使用encoding/binary包:
var i int16 = 41
b := make([]byte, 2)
binary.LittleEndian.PutUint16(b, uint16(i))
encoding/binary包提供了预先构建的函数,用于对所有固定大小的整数进行小端和大端编码,以及一些易于使用的函数,如果你使用的是读取器和写入器而不是字节切片。示例:
var i int16 = 41
err := binary.Write(w, binary.LittleEndian, i)
英文:
While FUZxxl's answer works, you can also use the encoding/binary package:
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)
答案2
得分: 23
如果你想获取int16的字节,可以尝试以下代码:
var i int16 = 41
var h, l uint8 = uint8(i>>8), uint8(i&0xff)
Go语言试图让编写依赖于平台属性(如字节顺序)的程序变得困难。因此,禁止使用类型转换来导致此类依赖(例如将字节数组与int16叠加)。
如果你真的想自讨苦吃,可以尝试使用unsafe包。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论