将 C 中的字符串文本文件转换为十六进制编码

Convert String Text File in C to Hexadecimal encoding

您好,我对 C 很陌生,但我正在尝试执行文件 IO 以读入加密函数。我需要的用例是这样的: 要读取的文件是这样的:例如 text.txt

AA 08 BB CC
BB 00 AA FA
30 //Continues like this

然后我需要解析这个文件并删除它们之间的间距,以便将其读入逐字段: [AA08] -> 1010 1010 0000 1000

最后,我需要复制文件条件并将密文写入类似的格式,每个字节文本之间有间距:我们称之为 hexa.txt

AA BB

到目前为止,这是我的阅读代码,但它不能正常工作。首先,我认为我应该使用 fscanf(fhex,"%X", &temp), 但是我无法让文件像这样读取

"AA" -> 170 这意味着将 Char 读取为十六进制数

即:A = 二进制 1010 或十进制 10 我想要的不是将明文中的“A”读取为字符,而是想读取“A”-> BIN:1010,或者如果可能的话,直接将上面的 hexa.txt 读取为一个单词,如:0xAA08、0xBBCC 等等上。

#include <stdio.h>
#include <time.h>
#include <stdint.h>

#define KEYSIZE 30  
#define WORDSIZE 16
typedef unsigned char HALFWORD;
typedef unsigned short WORD;
int main () {
  FILE * fhex = fopen("hexa.txt", "r");
  unsigned char ch, ch2;
  HALFWORD w = 0;
  int i = 0;
  while (1) {
    if (feof(fhex)) {
      break;
    }
    ch = fgetc(fhex);// hex value
    if (ch < 47 || ch > 70){
      continue;
    }
    ch2 = fgetc(fhex); // hex value
    printf("%d %d \n", ch, ch2); // value should be 10 10 then 11 11
    // left shift 4 bits and add the other hex digit
    HALFWORD w = (ch << 4) + ch2;
    if (i==0) {
      printf("%8d, Expected: 170 \n", w);
    } else {
      printf("%8d, Expected: 187 \n", w);
    }
    // Encryption code
    i++;
  }
  return 0;
}

编辑: 增加了清晰度和最小的可重复性

Edit2:添加评论

这里是一个完整的代码示例,用于读取您拥有的格式的文件。

我做了一些错误检查。还有一个函数 hexToInt,它将一串十六进制数字转换为无符号整数,跳过前面的空格(您不需要那个)并在找到的第一个非十六进制数字处停止。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

// Convert a string of ASCII hexadecimal digits to an integer.
// Skip white spaces in front of string and stop at the first no hex digit.
unsigned int hexToInt(const char* hex)
{
    unsigned int result = 0;
    unsigned char c;

    // First, skip spaces
    while (isspace(*hex))
        hex++;
    // Then convert hex digits until no more hex digit
    while (c = *hex++) {
        if (c >= '0' && c <= '9')
            result = (result << 4) + (c - '0');
        else if (c >= 'A' && c <= 'F')
            result = (result << 4) + (c + 10 - 'A');
        else if (c > 'a' && c <= 'f')
            result = (result << 4) + (c + 10 - 'a');
        else
            break;  // Not an hex digit, stop converting
    }
    return result;
}

int main()
{
    FILE* fhex = fopen("hexa.txt", "r");
    if (fhex == NULL) {
        perror("unable to open file");
        return 1;
    }
    char line[100];  // More than enough for one of our line
    int lineCnt = 0;
    unsigned short data[1000][2];

    // Read the file and build the array of words
    while (1) {
        if (fgets(line, sizeof(line) / sizeof(line[0]), fhex) == NULL) {
            // Read error, assume end of file
            break;
        }
        // File format is "AA 08 BB CC"  (4 hex digit couples separated by space)
        if ((strlen(line) != 12) || // There is a EOL character
            !isxdigit(line[0]) || !isxdigit(line[1]) || (line[2] != ' ') ||
            !isxdigit(line[3]) || !isxdigit(line[4]) || (line[5] != ' ') ||
            !isxdigit(line[6]) || !isxdigit(line[7]) || (line[8] != ' ') ||
            !isxdigit(line[9]) || !isxdigit(line[10])) {
            fprintf(stderr, "File format error on line %d (%s)\n", lineCnt + 1, line);
            return 1;
        }
        if (lineCnt >= (sizeof(data) / sizeof(data[0]))) {
            fprintf(stderr, "File is too big. Max lines is %d\n", lineCnt);
            return 1;
        }
        data[lineCnt][0] = (hexToInt(line + 0) << 8) + hexToInt(line + 3);
        data[lineCnt][1] = (hexToInt(line + 6) << 8) + hexToInt(line + 9);
        lineCnt++;
    }
    fclose(fhex);

    // Show data read
    for (int i = 0; i < lineCnt; i++)
        printf("Line %d = %X,%X\n", i + 1, data[i][0], data[i][1]);

    printf("Done.\n");
}