Skip to content

Instantly share code, notes, and snippets.

@nexus166
Created June 2, 2020 13:55
Show Gist options
  • Save nexus166/fce6477faf6abbbfc6be2d645f869169 to your computer and use it in GitHub Desktop.
Save nexus166/fce6477faf6abbbfc6be2d645f869169 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"fmt"
"os"
"strings"
"strconv"
)
func bitStringToBytes(s string) ([]byte, error) {
size := 8
ss := make([]string, 0, len(s)/size+1)
for len(s) > 0 {
if len(s) < size {
size = len(s)
}
ss, s = append(ss, s[:size]), s[size:]
}
var buf bytes.Buffer
for _, bs := range ss {
n, err := strconv.ParseUint(bs, 2, 8)
if err != nil {
return nil, err
}
buf.WriteByte(byte(n))
}
return buf.Bytes(), nil
}
func bytesToBitString(b []byte) string {
s := fmt.Sprintf("%08b", b)
return strings.ReplaceAll(s[1:len(s)-1], " ", "")
}
func main() {
s := "Hello, playground"
fmt.Printf("\nstring\n%s\n%b\n\n", s, []byte(s))
bitstr := bytesToBitString([]byte(s))
fmt.Printf("\nbitstring\n%s\n\n", bitstr)
b, err := bitStringToBytes(bitstr)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println(string(b))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment