//isSymbol表示有无符号
func BytesToInt (b []字节,isSymbol bool), (int,错误){
,if isSymbol {
,return bytesToIntS (b)
,}
,return bytesToIntU (b)
}//字节数(大端)组转成int(无符号的)
func bytesToIntU (b []字节),(int,错误),{
,if len (b),==, 3, {=,b 附加([]字节{0},b…)
,}
,bytesBuffer :=, bytes.NewBuffer (b)
,switch len (b), {
,case 1:
var tmp uint8
,err :=, binary.Read (bytesBuffer, binary.BigEndian,,, tmp)
,return int (tmp),犯错
,case 2:
var tmp uint16
,err :=, binary.Read (bytesBuffer, binary.BigEndian,,, tmp)
,return int (tmp),犯错
,case 4:
var tmp uint32
,err :=, binary.Read (bytesBuffer, binary.BigEndian,,, tmp)
,return int (tmp),犯错
,默认值:
,return 0, fmt.Errorf (“% s",,“BytesToInt bytes lenth is invaild !“)
,}
}//字节数(大端)组转成int(有符号)
func bytesToIntS (b []字节),(int,错误),{
,if len (b),==, 3, {=,b 附加([]字节{0},b…)
,}
,bytesBuffer :=, bytes.NewBuffer (b)
,switch len (b), {
,case 1:
var tmp int8
,err :=, binary.Read (bytesBuffer, binary.BigEndian,,, tmp)
,return int (tmp),犯错
,case 2:
var tmp int16
,err :=, binary.Read (bytesBuffer, binary.BigEndian,,, tmp)
,return int (tmp),犯错
,case 4:
var tmp int32
,err :=, binary.Read (bytesBuffer, binary.BigEndian,,, tmp)
,return int (tmp),犯错
,默认值:
,return 0, fmt.Errorf (“% s",,“BytesToInt bytes lenth is invaild !“)
,}
}//整形转换成字节
func IntToBytes (n int, b 字节),([]字节,错误),{
,switch b {
,case 1:
,tmp :=, int8 (n)
,bytesBuffer :=, bytes.NewBuffer([]字节{})
,binary.Write (bytesBuffer, binary.BigEndian,,, tmp)
,return bytesBuffer.Bytes(),零
,case 2:
,tmp :=, int16 (n)
,bytesBuffer :=, bytes.NewBuffer([]字节{})
,binary.Write (bytesBuffer, binary.BigEndian,,, tmp)
,return bytesBuffer.Bytes(),零
,case 3、4:
,tmp :=, int32 (n)
,bytesBuffer :=, bytes.NewBuffer([]字节{})
,binary.Write (bytesBuffer, binary.BigEndian,,, tmp)
,return bytesBuffer.Bytes(),零
,}
,return nil, fmt.Errorf (“IntToBytes b param is invaild")
}
<>强补充:golang整型,浮点数与字节转换
<强>使用场景:
在tcp协议传输中,为了防止粘包,需要先发送消息头,即先发送数据长度,在根据长度写真正的数据,然e,由于网络传输都是字节流,怎么将整型转为字节流呢?
<强>只需四步:
转换——int转int64
申请- - - - -申请一个字节缓冲
写入——按照二进制,向缓冲写入数据
取出- - - - -以字节流从缓冲中取出
func IntToBytes (n int)[]字节{
,数据:=int64 (n)//数据类型转换
,bytebuffer:=bytes.NewBuffer({})[]字节//字节集合
,binary.Write (bytebuffer, binary.BigEndian数据)//按照二进制写入字节
,return bytebuffer.Bytes()//返回字节结合
} <>强解码同样需两步:
1。创建一个以字节流为内容的缓冲区()
2。从缓冲区缓冲读取二进制编码的数据并赋给数据
func BytesToInt int (bs []字节){
,bytebuffer:=bytes.NewBuffer (bs),//根据二进制写入二进制结合
var data int64
,binary.Read (binary.BigEndian bytebuffer,和数据),//解码
,return int(数据)
} 上述内容就是利用golang怎么将整型转换成字节数组,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注行业资讯频道。