the issue convert buffer to hex string in c

358 views Asked by At

I'm trying to convert buffer to hex string in c as the below, the below image is the input file enter image description here 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?

1

There are 1 answers

6
Some programmer dude On BEST ANSWER

The major problem here is that your char type seems to be signed (if char is signed or unsigned is implementation specific). That means that values larger equal or larger than 0x80 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 an int it is sign-extended. So 0xff becomes 0xffffffff, which is then printed.

If you use unsigned char for your values instead, then values like 0xff are not extended when being promoted to unsigned int. So 0xff is promoted to 0x000000ff, and the leading zeroes are not printed.


Another issue is that you are using the wrong format for printf. The format "%x" is for unsigned int and not unsigned char. If you read e.g. this printf (and family) reference you will see a big table with all the formatting code and the different size prefixes for different types. To print an unsigned char you should use the hh prefix, as in "%hhx".