golang实现整型和字节数组之间的转换操作我就废话不多说了,⼤家还是直接看代码吧~
//isSymbol表⽰有⽆符号
func BytesToInt(b []byte, isSymbol bool) (int, error){
if isSymbol {
return bytesToIntS(b)
}
return bytesToIntU(b)
}
//字节数(⼤端)组转成int(⽆符号的)
func bytesToIntU(b []byte) (int, error) {
if len(b) == 3 {
b = append([]byte{0},b...)
}
go语言字符串转数组
bytesBuffer := bytes.NewBuffer(b)
switch len(b) {
case 1:
var tmp uint8
err := binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp), err
case 2:
var tmp uint16
err := binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp), err
case 4:
var tmp uint32
err := binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp), err
default:
return 0,fmt.Errorf("%s", "BytesToInt bytes lenth is invaild!")
}
}
//字节数(⼤端)组转成int(有符号)
func bytesToIntS(b []byte) (int, error) {
if len(b) == 3 {
b = append([]byte{0},b...)
}
bytesBuffer := bytes.NewBuffer(b)
switch len(b) {
case 1:
var tmp int8
err := binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp), err
case 2:
var tmp int16
err := binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp), err
case 4:
var tmp int32
err := binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp), err
default:
return 0,fmt.Errorf("%s", "BytesToInt bytes lenth is invaild!")
}
}
//整形转换成字节
func IntToBytes(n int,b byte) ([]byte,error) {
switch b {
case 1:
tmp := int8(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, &tmp)
return bytesBuffer.Bytes(),nil
case 2:
tmp := int16(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, &tmp)
return bytesBuffer.Bytes(),nil
case 3,4:
tmp := int32(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, &tmp)
return bytesBuffer.Bytes(),nil
}
return nil,fmt.Errorf("IntToBytes b param is invaild")
}
补充:golang整型,float与byte转换
使⽤场景:
在tcp协议传输中,为了防⽌粘包,需要先发送消息头,即先发送数据长度,在根据长度write真正的数据,然e,由于⽹络传输都是字节流,怎么将整型转为字节流呢?
只需四步:
转换----int转int64
申请----申请⼀个字节缓冲
写⼊----按照⼆进制,向缓冲写⼊数据
取出----以字节流从缓冲中取出
func IntToBytes(n int)[]byte{
data:=int64(n)//数据类型转换
bytebuffer:=bytes.NewBuffer([]byte{})//字节集合
binary.Write(bytebuffer,binary.BigEndian,data)//按照⼆进制写⼊字节
return bytebuffer.Bytes()//返回字节结合
}
解码同样需两步:
1.创建⼀个以字节流为内容的buffer()
2.从buf缓冲读取binary编码的数据并赋给data
func BytesToInt(bs []byte)int{
bytebuffer:=bytes.NewBuffer(bs) //根据⼆进制写⼊⼆进制结合
var data int64
binary.Read(bytebuffer,binary.BigEndian,&data) //解码
return int(data)
}
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。如有错误或未考虑完全的地⽅,望不吝赐教。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。