printf in dump routine
Piet van Oostrum
piet at ruuinf
Thu Mar 2 02:07:52 AEST 1989
In article <652 at dsacg2.UUCP>, nor1675 at dsacg2 (Michael Figg) writes:
` .
` long test_long;
` test_long = 1234;
` print_data((char *)&test_long,sizeof(test_long));
` .
` void print_data(pnt,num)
` char *pnt;
` int num;
` {
` int i;
` for(i = 0; i < num; i++)
` {
` printf("%02x",*(pnt + i));
` }
` }
Any clues as to why I'm getting this output and how to do it
` right? Thanks
The problem is that this code is highly unportable. So what you get depends
very much on the machine/compiler you have. There are two problems:
1. The ENDIAN-NESS of the machine. This means whether the bytes in a long
are addressed from the most significant byte or from the least
significant byte. What you are doing is taking a long and getting bytes
out of it. On a BIG-ENDIAN machine (such as the 68000) the first byte
you get is the upper (most significant) one, on a SMALL-ENDIAN (like the
8086) it is the lower byte. This explains the difference between the
Amiga and MS-DOS.
2. The char type that your compiler has. This can be signed or unsigned
(old compilers usually have only signed. In your case both compilers
apparently have signed chars, which means that a char that has its
8th bit set is passed to printf as a negative integer, which cuases
printf to print extra ff's (how many depends on the size of int, which
-- not surprisingly -- is 4 bytes on the Amiga and 2 bytes on MS-DOS).
This problem is easily solved by
printf("%02x",*(pnt + i) & 0xff);
or
printf("%02x",pnt[i] & 0xff);
--
Piet van Oostrum, Dept of Computer Science, University of Utrecht
Padualaan 14, P.O. Box 80.089, 3508 TB Utrecht, The Netherlands
Telephone: +31-30-531806. piet at cs.ruu.nl (mcvax!hp4nl!ruuinf!piet)
More information about the Comp.lang.c
mailing list