August 18th, 2003, 02:26 PM
convert binary to hex
I would like to read some binary numbers from a file and convert them to hexadecimal numbers and then write those hexadecimal numbers to another file. Can anyone help with a C script that would do this?
August 18th, 2003, 02:42 PM
Inside a computer, all numeric value are in binary. Please be more explicit in describing what you want to do.
My assumption of what you are asking: you want to --
1. Read values from a binary (ie, non-text) file
2. Output them those values to a text file in hexadecimal format.
Using fprintf to write to the output text file, use the %X or %x format specifier.
August 18th, 2003, 03:01 PM
It needs to be %02x per byte read, otherwise you may lose nibbles which are 0.
August 18th, 2003, 05:07 PM
you can fscanf("%d/* decimal*/") numbers and then fprintf("%x/*hexadecimal*/") numbers.
August 18th, 2003, 05:15 PM
why would he fscanf to an integer location when he can just read (or map) the file into memory & go through the data a lot faster (assuming the file is not HUGE)? And as I said before, %02x, not just %x; if reading 1 byte at a time, reading a nibble is ridiculous.
August 18th, 2003, 06:56 PM
Or %04X for 16-bit unsigned ints or %08X for unsigned longs. The thing is that we don't know whether he wants to display them byte-wise, as in a hex dump, or as short or long ints.
BTW, there's a real nice UNIX/Linux utility, xxd, which generates a hex dump of whatever you feed it. It also comes in a Windows port. Maybe that will do what he wants.
August 18th, 2003, 07:07 PM
Why just unsigned? Unsigned are almost always the same size as signed (in bits).
I thought my explanation was plenty, it hinted a single hexadecimal number represents 1 nibble, from that it's pretty easy to work out how many preceeding zero's should be used for each data size.
Last edited by xtor; August 18th, 2003 at 07:13 PM.
August 18th, 2003, 07:19 PM
According to my reference, by definition, the %x format specifier is unsigned.
August 18th, 2003, 07:42 PM
man pages state both %x and %X take unsigned integers (the %C outputs hexadecimal characters in capitals); although the hexadecimal output is sign independant, strange.