-2

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.

15
  • what do you mean by "binary"? Your example of changing a string to ***** and magically transforming it back doesn't make any sense Commented Jan 31, 2017 at 15:03
  • like this gist.github.com/hutt/8978333 (using php) Commented Jan 31, 2017 at 15:10
  • I still don't understand. A string is just a slice of bytes, and can be converted directly to []byte, it already is as "binary" as you can get. Please show exactly the output you expect. Commented Jan 31, 2017 at 15:16
  • 1101000 1100101 1101100 1101100 1101111 == hello in this php source Commented Jan 31, 2017 at 15:19
  • play.golang.org/p/5I2DIWisKF? Commented Jan 31, 2017 at 15:21

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

9 Comments

need try,catch to not show error if not binary.. example : fmt.Println(base2ToString("jdfgidjfigjdfidfg")) how fix this? show error : panic: strconv.ParseUint: parsing "jdfgidjf": invalid syntax??? how fix?
I purposely made it panic on invalid input. If you want to catch all errors, you are free to do so.
instead of panic, return the error and handle it. Have you gone over the basics of Go? Maybe take the Tour of Go
@LovePython: adler32 is a checksum, you can't "decode" it. Do you mean adler32.Checksum? Please take some time to learn the basics and how to check the documentation.
oh, Ok. i have a text(number). how can minify this? what hash is better and minify?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.