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

Linux kernel 如何将ascii转换为hexdump&;内核模块中的二进制到hextump,linux-kernel,binary,ascii,kernel-module,hexdump,Linux Kernel,Binary,Ascii,Kernel Module,Hexdump,我正在写一个内核模块, 模块支持将ASCII数据转换为Hexdump,将二进制数据转换为Hexdump,并通过cat进行打印。 不使用hexdump实用程序(util linux的一部分) 提前感谢。这是将ascii转换为十六进制的程序: */ #include <stdio.h> #include <stdlib.h> void hexdump(unsigned char *buffer, unsigned long index, unsigned long

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


提前感谢。

这是将ascii转换为十六进制的程序:

 */
 #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
*/
#包括
#包括
void hextump(无符号字符*缓冲区、无符号长索引、无符号长宽度)
{
无符号长i;
for(i=0;ilib/hextump.c和include/linux/kernel.h)是您的朋友。根据具体情况,检查%*ph。