从数组中读取两个字符作为C中的一个十六进制数

时间:2023-01-28 12:32:01

So I am working on an encryption/decryption project .
What I want to do is read in 2 characters from the line, and use them as one hex number to decrypt to the original hex value, and print to a file accordingly the proper ascii character value.. here's my code :

所以我正在做一个加密/解密项目。我要做的是从一行中读取两个字符,并使用它们作为一个十六进制数字来解密原始的十六进制值,并相应地打印到文件中适当的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
}

1 个解决方案

#1


0  

If you have a string like str[]="0120";, you could do

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

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

to read the contents of str two characters at a time, treat them as hexadecimal numbers and store them into the variables a and b.

要一次读取str两个字符的内容,请将它们视为十六进制数字,并将它们存储到变量a和b中。

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

would print

将打印

1, 32

%x format specifier is used to read as hexadecimal numbers and the 2 in %2x is used specify the width.

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

Now you can use fprintf() to write the values to file.

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

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

And you have a typo in the last printf(). The format specifier for char is %c not %C. But in this case, I used %d as the variables are of type int.

在最后的printf()中有一个错码。char的格式说明符是%c而不是%c。但是在本例中,我使用%d作为类型为int的变量。

#1


0  

If you have a string like str[]="0120";, you could do

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

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

to read the contents of str two characters at a time, treat them as hexadecimal numbers and store them into the variables a and b.

要一次读取str两个字符的内容,请将它们视为十六进制数字,并将它们存储到变量a和b中。

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

would print

将打印

1, 32

%x format specifier is used to read as hexadecimal numbers and the 2 in %2x is used specify the width.

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

Now you can use fprintf() to write the values to file.

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

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

And you have a typo in the last printf(). The format specifier for char is %c not %C. But in this case, I used %d as the variables are of type int.

在最后的printf()中有一个错码。char的格式说明符是%c而不是%c。但是在本例中,我使用%d作为类型为int的变量。