我就废话不多说了,大家还是直接看代码吧~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
//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") } |
使用场景:
在tcp协议传输中,为了防止粘包,需要先发送消息头,即先发送数据长度,在根据长度write真正的数据,然e,由于网络传输都是字节流,怎么将整型转为字节流呢?
只需四步:
转换----int转int64
申请----申请一个字节缓冲
写入----按照二进制,向缓冲写入数据
取出----以字节流从缓冲中取出
1
2
3
4
5
6
|
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
1
2
3
4
5
6
|
func BytesToInt(bs []byte)int{ bytebuffer:=bytes.NewBuffer(bs) //根据二进制写入二进制结合 var data int64 binary.Read(bytebuffer,binary.BigEndian,&data) //解码 return int(data) } |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。
原文链接:https://skaygo.blog.csdn.net/article/details/80751229