Xref: utzoo comp.lang.c:16673 comp.sys.amiga:30087 Path: utzoo!attcan!uunet!mcvax!hp4nl!ruuinf!piet From: piet@ruuinf (Piet van Oostrum) Newsgroups: comp.lang.c,comp.sys.amiga Subject: Re: printf in dump routine Keywords: printf, pointers Message-ID: <1165@ruuinf.UUCP> Date: 1 Mar 89 16:07:52 GMT References: <652@dsacg2.UUCP> Sender: piet@ruuinf.UUCP Reply-To: piet@ruuinf (Piet van Oostrum) Followup-To: comp.lang.c Organization: Dept of Computer Science, University of Utrecht, Holland Lines: 46 In-reply-to: nor1675@dsacg2.UUCP (Michael Figg) In article <652@dsacg2.UUCP>, nor1675@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@cs.ruu.nl (mcvax!hp4nl!ruuinf!piet)