gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:57:44 25 4
gpt4 key购买 nike

我正在尝试从二进制文件中读取一个简单的结构,并将其转换为十六进制。

我在尝试将内容打印到窗口中时遇到问题。 “ block ”数据是一个大块,所以我希望它在第一个 printf 中将大量二进制打印到窗口中,然后在第二个 printf 中将十六进制打印到窗口中。然而,它只打印一行 int,这绝对不是它应该是的十六进制(它应该是一个非常长的字符)

我想知道我做错了什么?我是否必须在每个字节上迭代 while 循环并将其转换为十六进制之前的 byte_array ?还是我的类型错误?

这是我的代码:

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);
}

最佳答案

二进制到十六进制应该在此代码中工作。它用 gcc 编译,但我没有测试它。我希望下面的代码可以帮助您按照您想要的方式使用二进制到十六进制。

#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);
}

关于c - 从二进制文件读取结构并转换为C中的十六进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39362227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com