I'm trying to convert buffer to hex string in c as the below,
the below image is the input file
it's a binary file.
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "fcntl.h"
#if defined(_MSC_VER)
#include <BaseTsd.h>
typedef SSIZE_T ssize_t;
#endif
#define BUFF_SIZE 5
int main()
{
char buff[BUFF_SIZE];
int fd;
ssize_t rd_size;
FILE *rfp;
FILE *ofp;
ofp = fopen("output.txt", "w");
rfp = fopen("test.bin", "rb");
while ( 4== (fread(buff, 1, 4, rfp)))
{
fprintf(ofp, "%02X%02X%02X%02X \n", buff[0], buff[1], buff[2], buff[3]);
}
fclose(ofp);
fclose(rfp);
return 0;
}
then I use above code, I've got bin to hex file but I've got the problem at result.
04002B2B
000001FFFFFFFF
00030003
00000000
00000000
00000000
00000300
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00500050
00500050
00500050
00500050
00000000
FFFFFF80002000
00000000
08700F00
00000000
00000000
00000001
00000002
00000003
00000004
00000005
00000006
00000007
FFFFFF800FFFFFFFF01E
087007FFFFFF80
00320032
0BFFFFFFB80820
00050005
2DFFFFFFC7114D
00FFFFFFC20118
00001B58
As you can see that the above file, especially I don't want to "000001FFFFFFFF " this output. But I don't know what am I supposed to do
update
I want to run in the linux. but if I make a execute file, I got the segmant error. Can you let me know what am I supposed to do?
The major problem here is that your
chartype seems to besigned(ifcharissignedorunsignedis implementation specific). That means that values larger equal or larger than0x80will be treated as negative values (with two's complement systems).And when you pass such a value to
printfand the value is promoted to anintit is sign-extended. So0xffbecomes0xffffffff, which is then printed.If you use
unsigned charfor your values instead, then values like0xffare not extended when being promoted tounsigned int. So0xffis promoted to0x000000ff, and the leading zeroes are not printed.Another issue is that you are using the wrong format for
printf. The format"%x"is forunsigned intand notunsigned char. If you read e.g. thisprintf(and family) reference you will see a big table with all the formatting code and the different size prefixes for different types. To print anunsigned charyou should use thehhprefix, as in"%hhx".