This question already has answers here:
printf adds extra `FFFFFF` to hex print from a char array [duplicate]
                                
                                    (3个答案)
                                
                        
                                4年前关闭。
            
                    
printf()函数打印前导ffffff(从技术上讲,我知道最高有效位带有符号,因此它一直被带到数据开始的地方)。但是我不知道如何摆脱它们,为什么会这样呢?

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));
  }
...


输出:

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


解决了:

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


输出:

UNIX> md 10000
 10000 7f 45 4c 46 01 02 01 00 00 00 00 00 00 00 00 00 .ELF............

最佳答案

强制转换为unsigned char,以使系统将*(adr+i)视为无符号,因此不会进行符号扩展。

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

09-26 07:54