2

So i started with a message as a string, turned it into a byte array and printed it, I've now lost the original string but have the string output of the byte array. I want my string back. (don't ask me why i did this or how... I didn't really, this is just for illustration purposes).

Essentially the bit I'm missing is a convenient way to turn the printed representation of a byte array back into a byte array.

See the example below to explain better what I'm trying to do (complete 'otherWay' func):

go playground

package main

import (
    "fmt"
)

func main() {
    // started with originalString and lost it
    originalString := "I'm a string I am!"

    // I have the output of 'oneWay()' in my clipboard, so could paste into code
    golangStringFormatOfByteArray := oneWay(originalString)
    fmt.Println("String as bytes:", golangStringFormatOfByteArray )

    // get original string back
    returnString := otherWay(golangStringFormatOfByteArray )
    fmt.Println("Original String:", returnString )

}

func oneWay(theString string) string {

    theStringAsBytes := []byte(theString)
    golangStringFormatOfByteArray := fmt.Sprintf("%v", theStringAsBytes)

    return golangStringFormatOfByteArray 
}

func otherWay(stringFormat string) string {

    // how do I get the original string back

    return "I want you back"
}
12
  • 2
    you can just do string(byteArray). String is defined as simply []byte, so that simple conversion should do the trick. Commented Sep 28, 2017 at 19:36
  • you mean this: not my original string - play.golang.org/p/cw39ai7S5_ Commented Sep 28, 2017 at 19:37
  • Oh, you actually printed it to the [34 23 45 56] format? Why? If you are converting it for debugging or something, don't discard the original. Commented Sep 28, 2017 at 19:38
  • 2
    You're not converting your string into its corresponding byte slice, you're turning into another string that just happens to be the default go format for printing a byte slice. What are you trying to do exactly? Commented Sep 28, 2017 at 19:39
  • 1
    If you are printing it a certain way for debugging, just print it, but don't overwrite the original value with your debug value. Commented Sep 28, 2017 at 19:53

1 Answer 1

9

Well, that was a fun exercise, if a little pointless:

s := "WAT"

// Output as bytes
b := []byte(s)
bs := fmt.Sprintf("%v", b)

// Read bytes
var bb []byte
for _, ps := range strings.Split(strings.Trim(bs, "[]"), " ") {
    pi,_ := strconv.Atoi(ps)
    bb = append(bb,byte(pi))
}

// Print result
fmt.Printf("%s -> %s -> %s",s,bs,bb)

https://play.golang.org/p/6cRYVJ7goD

WAT -> [87 65 84] -> WAT

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.