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. However, it just prints one line of an int that definitely isnt the hex it should be (it should be a very long char)
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? 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] = ' ';
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:%sn", res);
}
Binary to hex should work in this code. It compiles with gcc
but I didn't test it. 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("%Xn", 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);
}
链接地址: http://www.djcxy.com/p/72156.html
上一篇: 使用指针将字符串数组传递给函数