x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 264

# writing to file in hex

I am trying to write data to a file in hex. I use the following to write to the file:

unsigned int bfType = 0x424D;
fprintf(output, "%X", bfType);

but it actually writes '424D' to the file as characters, so upon viewing, the hex equivalent is, '34 32 34 44' As I said, I want to write to file in hex, not as chars.. ie, write '424D' to the file, and it would come up in characters as 'BM'. How do I go about doing this correctly??

Thanks.
0
Harliquen
• 6
• 4
• 2
1 Solution

Commented:
fprintf (output,"%c%c,(bfType/256),(bfType%256));

will write BM for 0x424d
0

Commented:
Use
fprintf (output,"%c%c",(bfType/256),(bfType%256));
0

Author Commented:
Adjusted points from 50 to 70
0

Author Commented:
Thanks, that does work, and I understand why.. but isn't there an easier way?? eg. what if:

bfType = 0x424D00FFA6B21201;

instead of stripping of hex digits one at a time by /256/256/256/256.. etc can't the whole number be written directly and not necessarily using fprintf, is there another statment that will do it (points have been increased due to increase in q)??

Thanks

0

Commented:
assuming your machine representation of integers uses the same byte ordering that you want for your output, you might
fwrite( &bfType, sizeof(bftype), 1, output );
or if you want to write a constant, you can
fprintf( output,"%s","\x42\x4D\x00\xFF\xA6\xB2\x12\x01" );
0

Commented:
Ozo is correct by using fwrite. Another possibilty would be

int i;
unsigned long x=0x424db2032
char *tmp;

tmp = (char *) &x

for (i=0,i<sizeof(x);i++)
printf ("%c",*(tmp+i));
}
0

Commented:
which has the advantage that if your machine's internal representation of integers happens to be the reverse of the byte ordering you want for output, you can change it to
for( i=sizeof(x);i-->0; )
0

Author Commented:
Thanks ozo, your comment is alot more detailed, and is what I was after. Please post it as an answer so I can give you the points.
0

Author Commented:
Thanks ozo, your comment is alot more detailed, and is what I was after. Please post it as an answer so I can give you the points.
0

Author Commented:
Yes, it does work. But ozo's answer is alot more acceptable.
0

Commented:
To Harlequin: I gave you a correct answer to your question. I gave you further information as you altered the question. So I claim the points. You could gave points to ozo too, but I gave you the correct answer.
0

Author Commented:
feck, sorry, I didn't realise it was you that posted the further info. How do I divide the points between people?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.