duandan5471 2019-05-02 20:44
浏览 1556
已采纳

Golang将字符串打印为字节数组

What's the fmt code for printing a string as an array of bytes?

If I have a marshaled json object, I can print bytes like so:

type Fakejs struct {
    Fake string `json:"fake"`
}

fjs := Fakejs {Fake:"abc"}
mjs, err := json.Marshal(fjs)
fmt.Println(mjs)

Produces

[123 34 102 97 107 101 34 58 34 97 98 99 34 125]

Which is what I want. However, with a regular string, I try this:

mystr := "{\"fake\":\"abc\"}"
fmt.Printf("mystr:\t %x 
", []byte(mystr))

And this produces:

7b2266616b65223a22616263227d

Which is not what I want. What is the "%x"-like format code that will printf the string as an array of bytes.

  • 写回答

1条回答 默认 最新

  • dqcd84732 2019-05-02 23:29
    关注

    https://play.golang.org/p/eQcZm57k1C1

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        mystr := "{\"fake\":\"abc\"}"
        fmt.Printf("mystr:\t %v 
    ", []byte(mystr))
    }
    

    prints

    mystr:   [123 34 102 97 107 101 34 58 34 97 98 99 34 125] 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探