2017-09-28 19:35
浏览 203


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 (

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"

图片转代码服务由CSDN问答提供 功能建议

所以我以一条消息作为字符串开始,将其转换为字节数组并打印出来,现在 丢失了原始字符串,但具有字节数组的字符串输出。 我要回我的绳子。 (不要问我为什么这样做或如何做……我不是真的,这只是出于说明的目的。)

基本上,我所缺少的是一种方便 将字节数组的打印表示形式转换回字节数组的方法。

请参见下面的示例,以更好地解释我要尝试执行的操作(完成“ otherWay”功能):< / p>


“ fmt” 
func main(){
 originalString:=“我是一个字符串 我是!“ 
 //我的剪贴板中有“ oneWay()”的输出,因此可以粘贴到代码中
 golangStringFormatOfByteArray:= oneWay(originalString)
 fmt.Println(”字符串作为字节:“  ,golangStringFormatOfByteArray)
 returnString:= otherWay(golangStringFormatOfByteArray)
 fmt.Println(“ Original String:”,returnString)
func oneWay(theString string  )字符串{
 theStringAsBytes:= [] byte(theString)
 golangStringFormatOfByteArray:= fmt.Sprintf(“%v”,theStringAsBytes)
func otherWay(stringFormat字符串) 字符串{
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanniu4106 2017-09-28 20:57

    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)

    WAT -> [87 65 84] -> WAT

    解决 无用
    打赏 举报

相关推荐 更多相似问题