-1

printf() function prints leading ffffff (technically I understand that most significant bit carries sign so it gets carried all the way to where data starts). But how to get rid of them I have no idea and why is it happening?

int mem_display(Cmd *cp, char *arguments)
{
  int i;
  char *adr;
  if (!sscanf(arguments,"%x",&adr))
  {
      return 0;
  }
  printf("%#0.8s ",arguments);

  for (i=0; i<16; i++) {
    printf("%02.x ",(unsigned int)*(adr+i));
  }
...

the output:

 % UNIX> md 10668 
/*calling function show memory location 0x10668*/
    OUT:
     10668 ffffffbc 10 20 ffffffe0 ffffffa0 40 ffffffa2 ffffffa0 44 ffffff9c 23 ffffffa0 20

solved:

printf("%0.2x ",(unsigned int)*(adr+i));

output:

UNIX> md 10000
 10000 7f 45 4c 46 01 02 01 00 00 00 00 00 00 00 00 00 .ELF............
A_P
  • 331
  • 3
  • 15
  • Why are you using a `.` and `(unsigned int)` is very likely wrong. – Iharob Al Asimi Sep 21 '15 at 01:09
  • You shall not dereference an address you just entered, that is _undefined behaviour_ (unless it is the same value you just printed from the same program execution). Also the format-specifier is wrong for a pointer and the type has to be `void *`. – too honest for this site Sep 21 '15 at 01:13

2 Answers2

3

Cast to unsigned char to have the system consider *(adr+i) as unsigned, so that no sign expansion will be done.

for (i=0; i<16; i++) {
    printf("%02.x ",(unsigned char)*(adr+i));
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

Please read the printf() manual, this is the correct way

printf("%02x ", (unsigned char) adr[i]);

Note: don't use this *(a + i) notation, and specially when you are casting it. It's not a bad way to dereference a pointer, it's just not appropriate in this particular situation.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97