如何将StringText转换为二进制并反之使用Go

如何将StringText转换为二进制并反之使用Go

问题描述:

i want Convert Text(type=String) To Binary(type=String) And Conversely Using Go

some userfull link : Golang: How to convert String to binary representation & Convert string to binary in Go

but i need another.

i want example convert a text like hello to binary. and next can convert then binary to first text(hello).

var hash_text := hash("hello")//example return *****
var unhash_text := unhash(hash_text);//return hello

like this gist.github.com/hutt/8978333 (using php)

also speed for me is importamt.

Convert each byte individually to its base 2 representation. You can use strconv.ParseUint to convert the base2 back to bytes.

func stringToBase2(s string) string {
    var buf bytes.Buffer
    for i := 0; i < len(s); i++ {
        fmt.Fprintf(&buf, "%08b", s[i])
    }
    return buf.String()
}

func base2ToString(s string) string {
    var out []byte
    for i := 0; i+8 <= len(s); i += 8 {
        b, err := strconv.ParseUint(s[i:i+8], 2, 8)
        if err != nil {
            panic(err)
        }
        out = append(out, byte(b))
    }
    return string(out)
}

https://play.golang.org/p/cLvoPHZ-hH