printf in dump routine

Edwin Hoogerbeets edwin at hcr.UUCP
Sat Mar 4 13:50:16 AEST 1989


In article <652 at dsacg2.UUCP> nor1675 at dsacg2.UUCP writes:
>I'm trying to pass a pointer to a variable
>that I want to dump in hex and the number of bytes to print:
>  
>    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));
>      }
>    }

Your problem is that *(pnt + i) has type char. Thus, a char is pushed
onto the stack and printf is called, right? Well, not really. First,
the char is promoted to a int, which under Lattice is 32 bits. But
wait! A char is a signed quantity, so the promotion dutifully sign
extends the char. Any character >= 128 has the high bit set, and this
bit gets copied during sign extension. You got "000004ffffffd2" because
the "d2" has the high bit set (and extended in the call to printf)
while the other bytes don't have the high bit set.

Your solution is simple:

Change your argument declaration to

unsigned char *pnt;

or better yet, 

register unsigned char *pnt;

How's that for a declaration!

Happy hacking,

Edwin
HCR co-op subterfuge team



More information about the Comp.lang.c mailing list