简体   繁体   English

从二进制文件读取结构并在C中转换为十六进制

[英]Read struct from binary file and convert to Hex in C

I'm trying to read a simple struct from a binary file, and turn it into hex. 我正在尝试从二进制文件中读取一个简单的结构,并将其转换为十六进制。

I'm running into problems trying to print things out into the window. 我在尝试将内容打印到窗口时遇到问题。 The "chunk" data is one big chunk, so I'm expecting it to print a lot of binary out into the window for the first printf and then hex for the 2nd printf. “块”数据是一个很大的块,因此我希望它在第一个printf的窗口中打印很多二进制,然后在第二个printf的窗口中输出十六进制。 However, it just prints one line of an int that definitely isnt the hex it should be (it should be a very long char) 但是,它只打印一行int,该行肯定不是十六进制的(应该是一个很长的字符)

I'm wondering what I'm doing wrong? 我想知道我在做什么错? Do I have to iterate with a while loop over every byte and turn it into a byte_array before hexing? 我必须在每个字节上进行一次while循环迭代并将其转换为byte_array,然后再进行混合吗? Or have I got my types wrong? 还是我输入的类型有误?

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

void myChunks(){

    struct chunkStorage
    {
        char chunk;     // ‘Chunk of Data’
    };

    unsigned long e;

            FILE *p;
            struct chunkStorage d;
            p=fopen(“myfile.txt”,”rb");
            fread(&d.chunk,sizeof(d.chunk),1,p);
            printf(d.chunk);
            e = hex_binary(d.chunk);
            printf(e);
            fclose(p);

}

int hex_binary(char * res){
    char binary[16][5] = {"0000", "0001", "0010", "0011", "0100", "0101","0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110","1111"};
    char digits [] = "0123456789abcdef";

    const char input[] = ""; // input value
    res[0] = '\0';
    int p = 0;
    int value =0;
    while(input[p])
    {
        const char *v = strchr(digits, tolower(input[p]));
        if(v[0]>96){
            value=v[0]-87;
        }
        else{
            value=v[0]-48;
        }
        if (v){
            strcat(res, binary[value]);
        }
        p++;
    }
    return res;
    //printf("Res:%s\n", res);
}

Binary to hex should work in this code. 二进制到十六进制应在此代码中起作用。 It compiles with gcc but I didn't test it. 它可以用gcc编译,但是我没有测试。 I hope the code below can help you use binary to hex the way you want. 我希望下面的代码可以帮助您使用二进制十六进制格式。

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

int binary2hex(char bin) {
    char *a = &bin;
    int num = 0;
    do {
        int b = *a == '1' ? 1 : 0;
        num = (num << 1) | b;
        a++;
    } while (*a);
    printf("%X\n", num);
    return num;
}

void main() {
    struct chunkStorage {
        char chunk;     // ‘Chunk of Data’
    };
    unsigned long e;
    FILE *p;
    struct chunkStorage d;
    p = fopen("myfile.txt", "rb");
    fread(&d.chunk, sizeof(d.chunk), 1, p);
    printf("%c", d.chunk);
    e = binary2hex(d.chunk);
    printf("%lu", e);
    fclose(p);
}

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

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