以下是利用标准库binary来进行编解码
解码
①使用bytes.NewReader/bytes.Buffer来存储要解码的ascii串
②使用binary.Read来解码
packagemain import( "bytes" "encoding/binary" "fmt" ) funcmain(){ varpifloat64 bpi:=[]byte{0x18,0x2d,0x44,0x54,0xfb,0x21,0x09,0x40} buf:=bytes.NewReader(bpi) err:=binary.Read(buf,binary.LittleEndian,&pi) //这里可以继续读出来存在变量里,这样就可以解码出来很多,读的次序和变量类型要对 //binary.Read(buf,binary.LittlEndian,&v2) iferr!=nil{ fmt.Println("binary.ReadFailed:",err) } fmt.Print(pi) //3.141592653589793 }
编码
①使用bytes.Buffer来存储编码生成的串
②使用binary.Write来编码存储在①的buf中
packagemain import( "bytes" "encoding/binary" "fmt" ) funcmain(){ varpifloat64=3.141592653589793 buf:=new(bytes.Buffer) err:=binary.Write(buf,pi) //这里可以继续往buf里写,都存在buf里 //binary.Write(buf,uint16(12345)) iferr!=nil{ fmt.Println("binary.ReadFailed:",err) } fmt.Print(buf.Bytes()) //[2445688425133964] }
Multi模式
解码
ing
编码
packagemain import( "bytes" "encoding/binary" "fmt" ) funcmain(){ buf:=new(bytes.Buffer) vardata=[]interface{}{ uint16(61374),int8(-54),uint8(254),} for_,v:=rangedata{ err:=binary.Write(buf,v) iferr!=nil{ fmt.Println("binary.WriteFailed:",err) } } fmt.Printf("%x",buf.Bytes()) //beefcafe这个是16进制串 //这里转换为了16进制整数的串? }