Brief introduction
Package binary implements simple translation between numbers and byte sequences and encoding and decoding of varints.
The Varint functions encode and decode single integer values using a variable-length encoding; Smaller values require fewer bytes. For a specification, see https://developers.google.com/protocol-buffers/docs/encoding.
Translation: binary packet, simple implementation of the conversion between the number and byte, varints between the encoding and decoding. To put it simply, Varints is a way to represent integer data using one or more bytes. The smaller the value itself, the less the number of bytes it occupies.
Use
- Conversion of numbers and bytes to each other
Numbers is translated by reading and writing fixed-size values. A fixed-size value is either a fixed-size arithmetic type (bool, int8, Uint8, Int16, float32, complex64, ...) or a array or struct containing only fixed-size values.
Translation: Converts a number by reading in and writing a fixed-length value. A fixed-length value that can be a value of a specified length, a specified length array, or a structure containing a specified length. The number type must be stated as, BOOL, int8, Uint8, Int16, float32, complex64, ..., specific to see the source code
package mainimport ("bytes""encoding/binary""fmt")func main() { by := []byte{0x00, 0x00, 0x03, 0xe8} var num int32 bytetoint(by, &num) fmt.Println(int(num), num) // 测试 int -> byte by2 := []byte{} var num2 int32 num2 = 333 by2 = inttobyte(&num2) fmt.Println(by2) // 测试 byte -> int var num3 int32 bytetoint(by2,&num3) fmt.Println(num3)}// byte 转化 intfunc bytetoint(by []byte, num *int32) { b_buf := bytes.NewBuffer(by) binary.Read(b_buf, binary.BigEndian, num)}// 数字 转化 bytefunc inttobyte(num *int32) []byte { b_buf := new(bytes.Buffer) binary.Write(b_buf, binary.BigEndian,num) return b_buf.Bytes()}