2013-09-23 70 views
3

我期待将C中的现有代码转换为执行以下操作:我正在尝试编写一个十六进制转储程序,该程序打印出地址:值可打印字符。 目前,数值的代码是打印的格式如下:一次打印十六进制数字2个字节

0003540: 05 04 06 75 6e 73 69 67 6e 65 64 20 63 68 61 72 ...unsigned char 

期望中的十六进制输出:在对

0003540: 0504 0675 6e73 6967 6e65 6420 6368 6172 ...unsigned char 

当前代码打印:

addr = 0; 
    while ((cnt = (long) 
    fread (buf, sizeof (unsigned char), 16, filein)) > 0) { 

    b = buf; 
    /* Print the address in hexadecimal. */ 
    fprintf (fileout, "%07lx ", addr); 
    addr = addr + 16; 
    /* Print 16 data items, in pairs, in hexadecimal. */ 
    cnt2 = 0; 
    for (m = 0; m < 16; m++) { 
     cnt2 = cnt2 + 1; 
     if (cnt2 <= cnt) { 
     fprintf (fileout, "%02x", *b++); 
     } 
     else { 
     fprintf (fileout, " "); 
     } 
     fprintf (fileout, " "); 
    } 
    /* Print the printable characters, or a period if unprintable. */ 
    fprintf (fileout, " "); 
    cnt2 = 0; 
    for (n = 0; n < 16; n++) { 
     cnt2 = cnt2 + 1; 
     if (cnt2 <= cnt) { 
     if ((buf[n] < 32) || (buf[n] > 126)) { 
      fprintf (fileout, "%c", '.'); 
     } 
     else { 
      fprintf (fileout, "%c", buf[n]); 
     } 
     } 
    } 
    fprintf(fileout, "\n"); 
    } 

我怎样才能改变这种代码来实现AB12 CD34格式? 谢谢!

+2

你就不能使用'fprintf中(FILEOUT, “%02X%02X”,* B ++,* B ++)'或类似的?我不确定你的变量名是什么...... – Tawnos

+0

你好,Tawnos,将更清楚地解释变量的完整代码可以在这里找到[链接](http://orion.math.iastate.edu/burkardt/c_src/ hexdump/hexdump.c) – simplicity

+2

@Tawnos这不是没有说明的行为吗? –

回答

2

使用模(余)运算符%来测试是否m是由2整除只写空间时,它是:

for (m = 0; m < 16; m++) { 
    if (m > 0 && m % 2 == 0) { 
    fprintf (fileout, " "); 
    } 
    fprintf (fileout, "%02x", *b++); 
} 

编辑3:

for (m = 0; m < 16; m++) { 
    if (m > 0 && m % 2 == 0) { 
    fprintf (fileout, " "); // space between every second byte 
    } 
    if (m < cnt) { 
    fprintf (fileout, "%02x", *b++); 
    } else { 
    fprintf (fileout, " "); // blank if run out of bytes on this line 
    } 
} 
+0

感谢Boann,但是你能否澄清这将适合以前的代码,或者它是否会完全取代它? if(cnt2 <= cnt)用于确保只将值打印为要转储十六进制字符的大小(由cnt表示)。因此,您是否可以澄清如何在保持if(cnt2 <= cnt)检查的同时仍然一次打印2对?谢谢! – simplicity

+0

@simplicity我不知道我跟着。你只需要16个字节,还是你想'cnt'字节,或者哪个更少,或者你想'cnt'字节,但每行16 * *? – Boann

+0

这将取决于哪一个更少,每条线最多16个。 – simplicity

0

我认为这是可以简化一下。例如,我会考虑开始是这样的:

#include <stdio.h> 
#include <ctype.h> 

int main(){ 
    char buffer[17]; 
    size_t bytes; 
    int i; 
    while (0 < (bytes = fread(buffer, 1, 16, stdin))) { 
     for (i = 0; i < bytes/2; i++) // print out bytes, 2 at a time 
      printf("%02x%02x ", buffer[i * 2], buffer[i * 2 + 1]); 
     if (i * 2 < bytes)    // take care of (possible) odd byte 
      printf("%02x ", buffer[i * 2]); 

     for (; i < 8; i++)    // right pad hex bytes 
      printf("  "); 

     for (i = 0; i < bytes; i++)  // change unprintable to '.' 
      if (!isprint(buffer[i])) 
       buffer[i] = '.'; 

     buffer[i] = '\0';    // terminate string 
     printf("\t%s\n", buffer); // print out characters 
    } 
    return 0; 
}