1
0

xxdi.pl 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env perl
  2. #
  3. # xxdi.pl - perl implementation of 'xxd -i' mode
  4. #
  5. # Copyright 2013 Greg Kroah-Hartman <gregkh@linuxfoundation.org>
  6. # Copyright 2013 Linux Foundation
  7. #
  8. # Released under the GPLv2.
  9. #
  10. # Implements the "basic" functionality of 'xxd -i' in perl to keep build
  11. # systems from having to build/install/rely on vim-core, which not all
  12. # distros want to do. But everyone has perl, so use it instead.
  13. #
  14. use strict;
  15. use warnings;
  16. my $indata;
  17. my $var_name = "stdin";
  18. my $full_output = (@ARGV > 0 && $ARGV[0] eq '-i') ? shift @ARGV : undef;
  19. {
  20. local $/;
  21. my $fh;
  22. if (@ARGV) {
  23. $var_name = $ARGV[0];
  24. open($fh, '<:raw', $var_name) || die("xxdi.pl: Unable to open $var_name: $!\n");
  25. } elsif (! -t STDIN) {
  26. $fh = \*STDIN;
  27. undef $full_output;
  28. } else {
  29. die "usage: xxdi.pl [-i] [infile]\n";
  30. }
  31. $indata = readline $fh;
  32. close $fh;
  33. }
  34. my $len_data = length($indata);
  35. my $num_digits_per_line = 12;
  36. my $outdata = "";
  37. # Use the variable name of the file we read from, converting '/' and '.
  38. # to '_', or, if this is stdin, just use "stdin" as the name.
  39. $var_name =~ s/\//_/g;
  40. $var_name =~ s/\./_/g;
  41. $var_name = "__$var_name" if $var_name =~ /^\d/;
  42. $outdata = "unsigned char $var_name\[] = { " if $full_output;
  43. for (my $key= 0; $key < $len_data; $key++) {
  44. if ($key % $num_digits_per_line == 0) {
  45. $outdata = substr($outdata, 0, -1)."\n ";
  46. }
  47. $outdata .= sprintf("0x%.2x, ", ord(substr($indata, $key, 1)));
  48. }
  49. $outdata = substr($outdata, 0, -2);
  50. $outdata .= "\n";
  51. $outdata .= "};\nunsigned int $var_name\_len = $len_data;\n" if $full_output;
  52. binmode STDOUT;
  53. print $outdata;