【发布时间】:2012-03-25 02:20:03
【问题描述】:
参考问题的第二个答案:How to convert from ASCII to Hex and vice versa?
我想将不同字符的char hex[3]等价保存如下:
char *str ="abcd";
// I want to get hex[3] of each character in above string and save into the following:
char str2[4]; // should contain hex values as : \x61 for a,\x62 for b,\x63 for c,\x64 for d
我该怎么做?
到目前为止,我尝试了以下方法:
int i;
char ch;
char hex[3];
for(i=0; i<strlen(str);i++) {
ch = charToHex(*(str+i), hex);
// now hex contains the first and second hex characters in hex[0] & hex[1]
// I need to save them in the first index of str2
// e.g. if hex[0] = 7 and hex[1] = f, then str2[0] should be "\x7f"
// -> how do I do this part ?
}
谢谢。
【问题讨论】:
-
这不是一个为我写代码的网站。你试过什么?你被困在哪里了?另请注意,字符串
"\\x61"可能不适合char[4]因为空终止符。 (我说“可能”,因为如果你愿意,你可以在没有空终止符的情况下工作,但这很尴尬,而且我怀疑这不是你想要的。) -
答案不会以固定的顺序出现——顺序取决于赞成票和反对票——所以“第二个答案”并不是对您所指内容的有用描述。为什么不使用底部的“链接”链接直接链接到您想到的答案?
-
@MarceloCantos 请查看更新后的问题
-
@Jake:
str2[0]的类型为char。它不能保存字符串"\\x7f"。如果您想将值0x7f存储为字符,那么您无非是原封不动地复制源数据,在这种情况下,您不妨直接写memcpy(str2, str, 4)。