Golang Imitation python pack/unpack

Source: Internet
Author: User
Tags unpack
This is a creation in Article, where the information may have evolved or changed.

Imperfect or perfect, especially high and low level conversion that (go and C binary higher status reverse need to convert, there is go int turn []byte length is 4 bit), hope the Bulls look after guidance

The project needs to be transferred through the socket client is go, the server side is Python, because of the need for packet unpacking, referring to Python written

Python's pack/unpack reference python uses struct to process binary (pack and unpack usage)

Package Includesimport ("bytes"    "encoding/binary"    "FMT"    _ "OS"    "StrConv"    "Strings") Type Protocolstruct{Format []string}//Sealing PackageFunc (P *protocol) Pack (args ...Interface{}) []byte{la:=len (args) LS:=Len (p.format) RET:= []byte{}    ifls >0&& La >0&& ls = =La { forI: =0; i < LS; i++ {            ifP.format[i] = ="H"{ret= Append (ret, IntToBytes2 (Args[i]. (int))...) } Else ifP.format[i] = ="I"{ret= Append (ret, INTTOBYTES4 (Args[i]. (int))...) } Else ifStrings. Contains (P.format[i],"s") {num, _:= StrConv. Atoi (Strings. TrimRight (P.format[i],"s")) RET= Append (ret, []byte(FMT. Sprintf ("%s%s", Args[i]. (string), strings. Repeat ("\x00", Num-len (Args[i]. (string)))))...) }        }    }    returnret}//UnpackingFunc (P *protocol) UnPack (msg []byte) []Interface{} {la:=Len (p.format) RET:= Make ([]Interface{}, LA)ifLa >0 {         forI: =0; I < LA; i++ {            ifP.format[i] = ="H"{Ret[i]= Bytes4toint (msg[0:2]) msg= msg[2: Len (msg)]} Else ifP.format[i] = ="I"{Ret[i]= Bytes4toint (msg[0:4]) msg= msg[4: Len (msg)]} Else ifStrings. Contains (P.format[i],"s") {num, _:= StrConv. Atoi (Strings. TrimRight (P.format[i],"s")) Ret[i]=string(msg[0: num]) Msg=Msg[num:len (msg)]}} }    returnRet}func (P*protocol) Size ()int{size:=0ls:=Len (P.format)ifls >0 {         forI: =0; i < LS; i++ {            ifP.format[i] = ="H"{size= size +2            } Else ifP.format[i] = ="I"{size= size +4            } Else ifStrings. Contains (P.format[i],"s") {num, _:= StrConv. Atoi (Strings. TrimRight (P.format[i],"s")) Size= size +num}} }    returnsize}//shaping into bytesFunc inttobytes (nint) []byte{m:=int32 (N) Bytesbuffer:= bytes. Newbuffer ([]byte{}) binary. Write (Bytesbuffer, Binary. Bigendian, M) GByte:=bytesbuffer.bytes ()returnGByte}//shaping into bytes 4 bitsFunc IntToBytes4 (nint) []byte{m:=int32 (N) Bytesbuffer:= bytes. Newbuffer ([]byte{}) binary. Write (Bytesbuffer, Binary. Bigendian, M) GByte:=bytesbuffer.bytes ()//C + + high-low conversionK: =4x:=Len (gbyte) NB:= Make ([]byte, K) forI: =0; I < K; i++{Nb[i]= gbyte[x-i-1]    }    returnNB}//shaping into bytes 2 bitsFunc IntToBytes2 (nint) []byte{m:=int32 (N) Bytesbuffer:= bytes. Newbuffer ([]byte{}) binary. Write (Bytesbuffer, Binary. Bigendian, M) GByte:=bytesbuffer.bytes ()//C + + high-low conversionK: =2x:=Len (gbyte) NB:= Make ([]byte, K) forI: =0; I < K; i++{Nb[i]= gbyte[x-i-1]    }    returnNB}//converting bytes into shapingFunc Bytestoint (b []byte)int{bytesbuffer:=bytes. Newbuffer (b)varx Int32 binary. Read (Bytesbuffer, Binary. Bigendian,&x)return int(x)}//4 bytes into shapingFunc Bytes4toint (b []byte)int{xx:= Make ([]byte,4)    ifLen (b) = =2{xx= []byte{b[0], b[1],0,0}    } Else{xx=B} m:=len (xx) NB:= Make ([]byte,4)     forI: =0; I <4; i++{Nb[i]= xx[m-i-1]} bytesbuffer:=bytes. Newbuffer (NB)varx Int32 binary. Read (Bytesbuffer, Binary. Bigendian,&x)return int(x)}

Call

P: =New(Protocol) P.format= []string{"H","H","I","16s","I","I","I"}h_byte:= P.pack (1,1,1,"ABC",1,0, Len (REQUEST_BUF)) Conn. Write (H_byte)

Additional:

intTurn binary FMT. Printf ("%08b\n", the)//01100001Binary ext int I, _:= StrConv. parseint ("1100001",2, +)// theintTurn []byteInttobytes ( +)//[0 0 3 232] 3*256+232=1000func inttobytes (nint) []byte{m:=int32 (N) Bytesbuffer:= bytes. Newbuffer ([]byte{}) binary. Write (Bytesbuffer, Binary. Bigendian, M) GByte:=bytesbuffer.bytes ()returnGByte} []byteturn int Bytestoint ([]byte{0,0,3,232})// +func bytestoint (b []byte)int{bytesbuffer:=bytes. Newbuffer (b)varx int32binary. Read (Bytesbuffer, Binary. Bigendian,&x)return int(x)}intTurnbyte byte( the)// the

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.