简体   繁体   English

从文本文件读取十六进制

[英]Reading hexadecimals from a text file

I am new to C and would like to ask the following question which I have struggled for a period of time. 我是C语言的新手,想问一下我一段时间以来一直苦苦挣扎的问题。 :( Please help! :( 请帮忙!

I want to read a plaintext file, passout.txt which contains a string of hexadecimal like: 我想读取一个纯文本文件passout.txt,其中包含一个十六进制字符串,例如:

A1B2C3D4E5403E9D501B223AD45523D6

and put them into an array like : 并将它们放入一个数组,如:

{A1, B2, C3, D4, E5, 40, 3E, 9D, 50, 1B, 22, 3A, D4, 55, 23, D6}

However, my current output is only : 但是,我当前的输出仅为:

{D4, 55, 23, D6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}

Only the last four hexidecimals can be retrieved only! 只能检索最后四个十六进制! I really don't know what mistakes I have made and I couldn't find any related solution from the web! 我真的不知道自己犯了什么错误,也无法从网络上找到任何相关的解决方案! Therefore, would anybody please help? 因此,有人可以帮忙吗?

Here's my code! 这是我的代码!

#include <stdio.h>
#include <string.h>
#include <openssl/aes.h>

#define AES_BLOCK_SIZE 16

void main()
{
    FILE *ifp;
    int i, rv;
    unsigned char in[AES_BLOCK_SIZE] = {0};

    ifp = fopen("passout.txt", "r");

    // loop and read the input file
    for(i = 0; i < AES_BLOCK_SIZE; i++)
    {
        rv = fscanf(ifp, "%X", &in[i]);
        if(rv != 1)
            i = AES_BLOCK_SIZE;
    }

    printf("Print result: \n");
    for(i=0; i < AES_BLOCK_SIZE; i++)
        printf("%X ",*(in+i));
    printf("\n");   

    fclose(ifp);
}
rv = fscanf(ifp, "%X", &in[i]);

change to 改成

rv = fscanf(ifp, "%2hhX", &in[i]);

for before C99 适用于C99之前

unsigned X;
rv = fscanf(ifp, "%2X", &X);
if(rv != 1)
    break;
in[i] = (unsigned char)X;

Your approach fails since the output format of sscanf is one number. 您的方法失败了,因为sscanf的输出格式是一个数字。

Your approach fails since the output format of sscanf is one number.You need to copy pairs of hex digits to a buffer and convert each pair to a byte. 您的方法失败了,因为sscanf的输出格式是一个数字。您需要将成对的十六进制数字复制到缓冲区中并将每对转换为一个字节。 This allows to convert any length of hex string. 这允许转换任何长度的十六进制字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM