如何将ascii转换为hexdump&内核模块中的二进制到hexdump

时间:2017-05-18 18:30:37

标签: linux-kernel binary ascii kernel-module hexdump

我正在写一个内核模块, 模块支持将ASCII数据转换为Hexdump,将二进制数据转换为Hexdump,并通过cat打印。 不使用hexdump实用程序(util-linux的一部分)

提前致谢。

1 个答案:

答案 0 :(得分:0)

这是将ascii转换为hex的程序:

 */
 #include <stdio.h>
 #include <stdlib.h>


 void hexdump(unsigned char *buffer, unsigned long index, unsigned long width)
 {
  unsigned long i;
  for (i=0;i<index;i++)
    {
    printf("%02x ",buffer[i]);
    }
  for (unsigned long spacer=index;spacer<width;spacer++)
    printf("    ");
  printf(": ");
  for (i=0;i<index;i++)
    {
    if (buffer[i] < 32) printf(".");
    else printf("%c",buffer[i]);
    }
  printf("\n");
 }


 int hexdump_file(FILE *infile,unsigned long start, unsigned long stop, unsigned long width)
  {
  char ch;
  unsigned long f_index=0;
  unsigned long bb_index=0;
  unsigned char *byte_buffer = malloc(width);
  if (byte_buffer == NULL)
    {
    printf("Could not allocate memory for byte_buffer\n");
    return -1;
    }
  while (!feof(infile))
    {
    ch = getc(infile);  
    if ((f_index >= start)&&(f_index <= stop))
    {
     byte_buffer[bb_index] = ch;
     bb_index++;
    }
    if (bb_index >= width)
    {
      hexdump(byte_buffer,bb_index,width);
      bb_index=0;
    }   
    f_index++;  
    }
  if (bb_index)
    hexdump(byte_buffer,bb_index,width);
  fclose(infile);
  free(byte_buffer);
  return 0;
 }


 int main(int argc, char *argv[])
 {
  if (argc != 5)
    {
    printf("Usage: hexdump <infile> <start> <end> <width>\n");
    return 0;
    }
  FILE *infile=fopen(argv[1],"rb");
  if (infile==(FILE *)NULL)
    {
    printf("Error opening input file %s\n",argv[1]);
    return 0;
    }
  printf("Filename: \"%s\"\n",  argv[1]);
  printf("Start : %lu\n",   atoi(argv[2]));
  printf("End   : %lu\n",   atoi(argv[3]));
  printf("Bytes per Line: %lu\n",atoi(argv[4]));  
  int result = hexdump_file(infile,atoi(argv[2]),atoi(argv[3]),atoi(argv[4]));
  return 0;
 }


Run output:

 $ hexdump hexdump.c 0 100 16
 Filename: "hexdump.c"
 Start : 0
 End    : 100
 Bytes per Line: 16
 2f 2a 0d 0a 20 20 54 68 69 73 20 65 6e 74 72 79 : /*..  This entry
 20 63 6f 6e 74 61 69 6e 73 20 63 65 72 74 61 69 :  contains certai
 6e 20 66 75 6e 63 74 69 6f 6e 61 6c 69 74 79 20 : n functionality
 74 68 65 20 6f 74 68 65 72 73 20 6d 61 79 20 6e : the others may n
 6f 74 2e 0d 0a 20 20 20 20 2a 20 54 68 65 20 73 : ot...    * The s
 74 6f 70 2d 73 74 61 72 74 20 73 70 61 6e 20 64 : top-start span d
 6f 65 73 20 6e               : oes n

谢谢&amp;问候 Satish.G