一次打印十六进制数字2个字节

时间:2013-09-23 01:21:05

标签: c++ c

我希望转换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格式? 谢谢!

2 个答案:

答案 0 :(得分:2)

使用modulo(余数)运算符%来测试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
  }
}

答案 1 :(得分: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;
}