美文网首页
Go语言:[]byte 与 Int16 的相互转换

Go语言:[]byte 与 Int16 的相互转换

作者: 白祤星 | 来源:发表于2019-08-28 11:52 被阅读0次

代码实例:



import (
    "encoding/binary"
)

func main() {
    // 保存 int16 数据
    i := int16(233)

    // 将 int16 转换为 byte 数据,并输出
    b := Int16ToBytes(i)
    println(b)

    // 输出 byte 转换后 int16 数据
    println(BytesToInt16(b))
}

func Int16ToBytes(i int16) []byte {
    buf := make([]byte, 8)
    binary.BigEndian.PutUint16(buf, uint16(i))
    return buf
}

func BytesToInt16(buf []byte) int16 {
    return int16(binary.BigEndian.Uint16(buf))
}

相关文章

网友评论

      本文标题:Go语言:[]byte 与 Int16 的相互转换

      本文链接:https://www.haomeiwen.com/subject/ohepectx.html