
有人可以告诉我哪里出了问题吗?
我无法通过字符串转换来转换由哈希求和函数生成的字节数组,我必须使用 sprintf。
这是代码片段:
f, _ := os.Open(filename)
hash := md5.New()
io.Copy(hash, f)
hashStringGood := fmt.Sprintf("%x", hash.Sum(nil))
hashStringJunk := string(hash.Sum(nil)[:])hasstringgood 将导致 d41d8cd98f00b204e9800998ecf8427e
hashstringjunk 将导致 ��ُ�� ���b~
当您将随机二进制数据转换为没有编码方案的字符串时,数据不太可能映射到可打印字符序列。
来自 fmt 包的 %x 动词是对二进制数据进行十六进制编码的便捷方法。来自fmt 包文档中动词定义的“字符串和字节切片”部分: p>
%s the uninterpreted bytes of the string or slice %q a double-quoted string safely escaped with go syntax %x base 16, lower-case, two characters per byte
或者,您可以使用嵌套在 encoding 包下的包对数据进行编码:
package main
import (
"crypto/md5"
"encoding/base64"
"encoding/hex"
"fmt"
)
func main() {
hash := md5.sum([]byte("input to be hashed"))
fmt.printf("using %%s verb: %s\n", hash)
fmt.printf("using %%q verb: %q\n", hash)
fmt.printf("using %%x verb: %x\n", hash)
hexhash := hex.encodetostring(hash[:])
fmt.printf("converted to a hex-encoded string: %s\n", hexhash)
base64hash := base64.stdencoding.encodetostring(hash[:])
fmt.printf("converted to a base64-encoded string: %s\n", base64hash)
}
输出
Using %s verb: �����Q���6���5� Using %q verb: "\x8d\xa8\xf1\xf8\x06\xd3Q\x9d\xa1\xe46\xdb\xfb\x9f5\xd7" Using %x verb: 8da8f1f806d3519da1e436dbfb9f35d7 Converted to a hex-encoded string: 8da8f1f806d3519da1e436dbfb9f35d7 Converted to a base64-encoded string: jajx+AbTUZ2h5Dbb+5811w==
以上就是GO 怪异将 Btye 数组从 MD5 哈希值转换为字符串的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号