xxdi.pl 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/env perl
  2. #
  3. # xxdi.pl - perl implementation of 'xxd -i' mode
  4. #
  5. # Copyright 2013 Greg Kroah-Hartman <[email protected]>
  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. sub slurp {
  17. my $file = shift;
  18. open my $fh, '<', $file or die;
  19. local $/ = undef;
  20. my $cont = <$fh>;
  21. close $fh;
  22. return $cont;
  23. }
  24. my $indata = slurp(@ARGV ? $ARGV[0] : \*STDIN);
  25. my $len_data = length($indata);
  26. my $num_digits_per_line = 12;
  27. my $var_name;
  28. my $outdata;
  29. # Use the variable name of the file we read from, converting '/' and '.
  30. # to '_', or, if this is stdin, just use "stdin" as the name.
  31. if (@ARGV) {
  32. $var_name = $ARGV[0];
  33. $var_name =~ s/\//_/g;
  34. $var_name =~ s/\./_/g;
  35. } else {
  36. $var_name = "stdin";
  37. }
  38. $outdata .= "unsigned char $var_name\[] = {";
  39. # trailing ',' is acceptable, so instead of duplicating the logic for
  40. # just the last character, live with the extra ','.
  41. for (my $key= 0; $key < $len_data; $key++) {
  42. if ($key % $num_digits_per_line == 0) {
  43. $outdata .= "\n\t";
  44. }
  45. $outdata .= sprintf("0x%.2x, ", ord(substr($indata, $key, 1)));
  46. }
  47. $outdata .= "\n};\nunsigned int $var_name\_len = $len_data;\n";
  48. binmode STDOUT;
  49. print {*STDOUT} $outdata;