douyue3800 2017-04-18 00:27
浏览 360
已采纳

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

I am attempting to escape a specific hex value in a golang string. The function call looks something like this:

Insert(0, "\x00\x00\x00IHDR\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")

The problem arises when the language interprets the "\xDA" hex escape. Instead of correctly escaping to a Ú value, it is escaped to � (the Replacement Character).

I ensured this is what was occuring in the following playground example:

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

This snippet, when run, prints

�
Hex conf of '218' is 'da'
Ú

Am I missing something here? The fact that "\xDA" is being escaped to a value of 65533 is throwing off my entire program, which relies on the CRC32 and some other checksums. This does not occur in the javascript version of this program (which itself is a translation from James compface program, written in C).

Here is the playground link: https://play.golang.org/p/c-XMK68maX

  • 写回答

3条回答 默认 最新

  • dongpu4141 2017-04-18 01:22
    关注

    Go strings are just a series of bytes, but when an encoding is needed, it's assumed to be utf8. The value \xda isn't a valid utf8 character, so when printing it's converted to the unicode.ReplacementCharacter "�"

        ReplacementChar = '\uFFFD'     // Represents invalid code points.
    

    If you want the rune value of \xda in a string literal, use a unicode escape: \u00DA, or use the utf8 encoded: \xc3\x9a, or use the character itself: Ú.

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

    If you actually want a single byte value of \xda in your string, that is what you have and the printed character is inconsequential.

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

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100