douping3891 2017-09-28 19:35
浏览 250
已采纳

将字节数组的golang字符串格式转换回原始字节数组

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"
}
  • 写回答

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)
    

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

    WAT -> [87 65 84] -> WAT

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵