转义字符串文字中的十六进制值

Joh*_*can 0 string hex escaping go

我试图在 golang 字符串中转义特定的十六进制值。函数调用看起来像这样:

Insert(0, "\x00\x00\x00\rIHDR\x00\x00\x000\x00\x00\x000\b\x03")
Insert(25, "\x00\x00\x00\x06PLTE")
Insert(43, "\x00\x00\x00\x02tRNS")
Insert(57, "\x00\x00\t;IDATx\xDA\x010\t\xCF\xF6") // problem line
Insert(2432, "\x00\x00\x00\x00IEND")
Run Code Online (Sandbox Code Playgroud)

当语言解释“\xDA”十六进制转义时会出现问题。它没有正确转义为 Ú 值,而是转义为 ? (替换字符)。

我确保这是以下操场示例中发生的情况:

fmt.Println("\xDA")
i := 218
h := fmt.Sprintf("%x", i)
fmt.Printf("Hex conf of '%d' is '%s'\n", i, h)  
fmt.Println(string(i))
Run Code Online (Sandbox Code Playgroud)

此代码段在运行时打印

?
Hex conf of '218' is 'da'
Ú
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么吗?"\xDA" 被转义为 65533 的事实正在抛弃我的整个程序,它依赖于 CRC32 和一些其他校验和。这不会发生在这个程序的javascript 版本中(它本身是 James compface 程序的翻译,用 C 编写)。

这是游乐场链接:https : //play.golang.org/p/c-XMK68maX

Jim*_*imB 6

Go 字符串只是一系列字节,但是当需要编码时,它被假定为 utf8。该值\xda不是有效的 utf8 字符,因此在打印时将其转换为unicode.ReplacementCharacter“?”

    ReplacementChar = '\uFFFD'     // Represents invalid code points.
Run Code Online (Sandbox Code Playgroud)

如果您想要\xda字符串文字中的 rune 值,请使用 unicode escape: \u00DA,或使用 utf8 编码的: \xc3\x9a,或使用字符本身: Ú

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

如果您确实想要\xda字符串中的单个字节值,那就是您所拥有的,并且打印的字符无关紧要。