【发布时间】:2018-01-18 15:36:40
【问题描述】:
当你在 C 中有字符串时,你可以在里面添加直接的十六进制代码。
char str[] = "abcde"; // 'a', 'b', 'c', 'd', 'e', 0x00
char str2[] = "abc\x12\x34"; // 'a', 'b', 'c', 0x12, 0x34, 0x00
两个示例的内存都有 6 个字节。现在如果你想在十六进制输入后添加值[a-fA-F0-9],问题就存在了。
//I want: 'a', 'b', 'c', 0x12, 'e', 0x00
//Error, hex is too big because last e is treated as part of hex thus becoming 0x12e
char problem[] = "abc\x12e";
可能的解决方案是在定义后替换。
//This will work, bad idea
char solution[6] = "abcde";
solution[3] = 0x12;
这可以工作,但它会失败,如果你把它写成const。
//This will not work
const char solution[6] = "abcde";
solution[3] = 0x12; //Compilation error!
如何在\x12之后正确插入e而不触发错误?
我为什么要问?当您想将 UTF-8 字符串构建为常量时,如果它大于 ASCII 表可以容纳的大小,则必须使用字符的十六进制值。
【问题讨论】:
-
重复:stackoverflow.com/questions/35180528/…。我将关闭那个,因为我认为这里发布的答案更完整,答案中引用了标准而不是 cmets。