我就废话不多说了,大家还是直接看代码吧~
//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...)
}
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)
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持软件开发网。如有错误或未考虑完全的地方,望不吝赐教。
您可能感兴趣的文章:Go语言string,int,int64 ,float之间类型转换方法go语言中int和byte转换方式golang int 转float 强转和高精度转操作