簡介
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.
翻譯:binary 包,簡單的實現了數字和byte之間的轉化;varints之間的編碼和解碼。簡單說一下,varints是一種使用一個或多個位元組表示整型資料的方法。其中數值本身越小,其所佔用的位元組數越少。
使用
Numbers are 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 an array or struct containing only fixed-size values.
翻譯:通過讀入和寫入固定長度的值來轉化數字。固定長度的值,既可以是指定長度的值,也可以是指定長度數組,也可以是包含指定長度結構體。數字類型必須申明為,bool, int8, uint8, int16, float32, complex64, ...,具體可以去看源碼
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()}