【问题标题】:Read two char from array as one hex number in C从数组中读取两个字符作为 C 中的一个十六进制数
【发布时间】:2018-07-05 09:28:59
【问题描述】:

所以我正在做一个加密/解密项目。
我想要做的是从行中读取 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
}

【问题讨论】:

  • 回车是'\r',换行是'\n'"/n" 只是斜线 & n
  • 签出strtol
  • 什么是i((tmp + i*2) + 16) 应该是什么?
  • ((tmp + i*2) + 16) 等价于&tmp[i*2 + 16]。但由于 tmp 仅包含 2 个字符,因此您在初始化部分之外访问。
  • @Barmar 这是一个循环来检查字符直到它到达行尾。 ((tmp i*2) + 16) 尝试让它一次访问数组的两个元素以将 16 添加到

标签: c arrays char int hex


【解决方案1】:

如果你有一个像str[]="0120"; 这样的字符串, 你可以这样做

int a, b;
sscanf(str, "%2x%2x", &a, &b);

一次读取str两个字符的内容,把它们当作十六进制数,存入变量ab中。

printf("\n%d, %d", a, b);

会打印

1, 32

%x 格式说明符用于读取为十六进制数,%2x 中的2 用于指定宽度。

现在您可以使用fprintf() 将值写入文件。

fprintf(output, "%d %d", a, b);

您在最后一个printf() 中有错字。 char 的格式说明符是 %c 而不是 %C。但在这种情况下,我使用了%d,因为变量的类型是int

【讨论】:

    猜你喜欢
    • 2015-12-20
    • 2018-09-08
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多