This is a creation in Article, where the information may have evolved or changed.
Effect
Converts a byte or byte array into the form of a string 01, with a byte represented by 8 "0" or "1" characters. Like what:
BYTE (3) –> "00000011"
[]byte{1,2,3}–> "[00000001 00000010 00000011]"
"[00000011 10000000]" –> []byte{0x3, 0x80}
Open Source Library Biu
In fact, I've encapsulated it in an open source library (Biu), one of these features:
//byte/[]byte -> stringbs := []byte{1, 2, 3//[00000001 00000010 00000011]fmt.Println(biu.ByteToBinaryString(byte(3//00000011//string -> []byte"[00000011 10000000]"bs := biu.BinaryStringToBytes(s)fmt.Printf("%#v\n"//[]byte{0x3, 0x80}
Code implementation
Const(zero =byte(' 0 ') One =byte(' 1 ') LSB =byte('[')//left square bracketsRSB =byte(']')//Right square bracketsSpace =byte(' '))varUint8arr[8]uint8//Errbadstringformat represents a error of input string ' s format is illegal.varErrbadstringformat = errors. New ("Bad string format")//erremptystring represents a error of empty input string.varerremptystring = errors. New ("empty string")funcInit () {Uint8arr[0] = -Uint8arr[1] = -Uint8arr[2] = +Uint8arr[3] = -Uint8arr[4] =8Uint8arr[5] =4Uint8arr[6] =2Uint8arr[7] =1}//Append bytes of string in binary format.funcAppendbinarystring (BS []byteBbyte) []byte{varAbyte forI: =0; I <8; i++ {a = b b <<=1b >>=1 SwitchA CaseB:bs =Append(BS, Zero)default: bs =Append(BS, one)} b <<=1}returnBs//Bytetobinarystring get the string in binary format of a byte or uint8.funcBytetobinarystring (bbyte)string{buf: = Make([]byte,0,8) BUF = Appendbinarystring (buf, B)return string(BUF)}//Bytestobinarystring get the string in binary format of a []byte or []int8.funcBytestobinarystring (BS []byte)string{L: =Len(BS) BL: = L*8+ L +1BUF: = Make([]byte,0, bl) BUF =Append(BUF, LSB) for_, B: =RangeBS {buf = appendbinarystring (buf, b) buf =Append(BUF, Space)} Buf[bl-1] = RSBreturn string(BUF)}//Regex for delete useless string which are going to being in binary format.varRbdel = RegExp. Mustcompile (' [^01] ')//Binarystringtobytes get the binary bytes according to the//input string which is in binary format.funcBinarystringtobytes (Sstring) (BS []byte) {if Len(s) = =0{Panic(erremptystring)} s = rbdel.replaceallstring (S,"") L: =Len(s)ifL = =0{Panic(Errbadstringformat)} MO: = l%8L/=8 ifMo! =0{l++} bs = Make([]byte,0, l) Mo =8-MovarNuint8 forI, B: =Range[]byte(s) {m: = (i + MO)%8 SwitchD = CaseOne:n + = Uint8arr[m]}ifm = =7{bs =Append(BS, n) n =0} }return}