drj14664 2019-07-08 16:21
浏览 2454
已采纳

解码base64并将其编码为十六进制

I have following code which decodes base64 and then encodes it to hex.

doc_id := "Can35qPeFkm9Xgmp9+aj3g=="
base64_decode, err := base64.StdEncoding.DecodeString(doc_id)
if err != nil {
log.Fatal("error:", err)
}
base64_decoded := fmt.Sprintf("%q", base64_decode)
fmt.Printf("base_decoded %v
", base64_decoded)



src := []byte(base64_decoded)
fmt.Println(src)
hex_encode := make([]byte, hex.EncodedLen(len(src)))
hex.Encode(hex_encode, src)
hex_encoded := fmt.Sprintf("%s", hex_encode)
fmt.Printf("hex_encoded %v", hex_encoded)

where doc_id is base64 format. base64_decoded is its decoded value. I have to encode it to hex, so i pass it to src.

The problem is when i pass the identifier base64_decoded to src i get wrong when i pass in the value that base64_decoded is holding i get correct answer. for example: if i get base64_decoded value as "\x11z\xc0[d~\xfcK\xb1\xf8\x11z\xc0[d~" if i pass its value which is "\x11z\xc0[d~\xfcK\xb1\xf8\x11z\xc0[d~", i get correct answer 117ac05b647efc4bb1f8117ac05b647e

if i pass the variable holding "\x11z\xc0[d~\xfcK\xb1\xf8\x11z\xc0[d~" i get wrong answer 225c7831317a5c7863305b647e5c7866634b5c7862315c7866385c7831317a5c7863305b647e22dn

Has it got something with this assignment base64_decoded := fmt.Sprintf("%q", base64_decode)

what am i doing wrong

  • 写回答

2条回答 默认 最新

  • dongzhang2150 2019-07-08 16:35
    关注

    Use the following code:

    doc_id := "Can35qPeFkm9Xgmp9+aj3g=="
    base64_decode, err := base64.StdEncoding.DecodeString(doc_id)
    if err != nil {
        log.Fatal("error:", err)
    }
    fmt.Println(hex.EncodeToString(base64_decode))
    

    Directly encode the bytes in base64_decode as hex.

    The call to fmt.Sprintf("%q", base64_decode) returns a string with the bytes escaped per Go's string literal rules. In the general case, the bytes in the returned string are not equal to the bytes in base64_decode. For example, the input byte 0x11 is escaped to the four bytes \x11.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格