3

我正在寻找转换 C 中的现有代码以执行以下操作:我正在尝试编写一个十六进制转储程序来打印地址:值可打印字符。目前,值的代码以以下格式打印:

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 格式?谢谢!

4

2 回答 2

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
  }
}
于 2013-09-23T01:25:01.717 回答
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;
}
于 2013-09-23T04:41:38.930 回答