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
char
type seems to besigned
(ifchar
issigned
orunsigned
is implementation specific). That means that values larger equal or larger than0x80
will be treated as negative values (with two's complement systems).And when you pass such a value to
printf
and the value is promoted to anint
it is sign-extended. So0xff
becomes0xffffffff
, which is then printed.If you use
unsigned char
for your values instead, then values like0xff
are not extended when being promoted tounsigned int
. So0xff
is 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 int
and 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 char
you should use thehh
prefix, as in"%hhx"
.