所以我正在研究一个加密/解密项目。
我想要做的是从该行读取 2 个字符,并将它们用作一个十六进制数字来解密为原始十六进制值,并相应地将正确的 ascii 字符值打印到文件中。这是我的代码:
sscanf(lineFromFile, "%2C", tmp);
//check carriage return new line as per outline
if(strcmp(tmp, "\n") == 0) {
fprintf(output, "%c", tmp);
}
//Check for tab whcih is set to TT in encryption scheme
if (strcmp(tmp, "TT") == 0) {
fprintf(output, "\t");
}
else {
outchar = ((tmp + i*2) + 16);
if (outchar > 127) {
outchar = (outchar - 144) + 32;
}
fprintf(output, "%C", outchar); //print directly to file
}
最佳答案
如果您有一个类似 str[]="0120";
的字符串,
你可以做
int a, b;
sscanf(str, "%2x%2x", &a, &b);
一次读取str
中的两个字符,将其视为十六进制数并将其存储到变量a
和b
中.
printf("\n%d, %d", a, b);
会打印
1, 32
%x
格式说明符用于读取十六进制数字,%2x
中的 2
用于指定宽度。
现在您可以使用fprintf()
将值写入文件。
fprintf(output, "%d %d", a, b);
最后一个 printf()
中有一个拼写错误。 char
的格式说明符是 %c
而不是 %C
。但在本例中,我使用了 %d
,因为变量的类型为 int
。
关于c - 从数组中读取两个字符作为C中的一个十六进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48454614/