scripts: add xxdi.pl
[openwrt/staging/dedeckeh.git] / scripts / xxdi.pl
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
15 use strict;
16 use warnings;
17 use File::Slurp qw(slurp);
18
19 my $indata = slurp(@ARGV ? $ARGV[0] : \*STDIN);
20 my $len_data = length($indata);
21 my $num_digits_per_line = 12;
22 my $var_name;
23 my $outdata;
24
25 # Use the variable name of the file we read from, converting '/' and '.
26 # to '_', or, if this is stdin, just use "stdin" as the name.
27 if (@ARGV) {
28 $var_name = $ARGV[0];
29 $var_name =~ s/\//_/g;
30 $var_name =~ s/\./_/g;
31 } else {
32 $var_name = "stdin";
33 }
34
35 $outdata .= "unsigned char $var_name\[] = {";
36
37 # trailing ',' is acceptable, so instead of duplicating the logic for
38 # just the last character, live with the extra ','.
39 for (my $key= 0; $key < $len_data; $key++) {
40 if ($key % $num_digits_per_line == 0) {
41 $outdata .= "\n\t";
42 }
43 $outdata .= sprintf("0x%.2x, ", ord(substr($indata, $key, 1)));
44 }
45
46 $outdata .= "\n};\nunsigned int $var_name\_len = $len_data;\n";
47
48 binmode STDOUT;
49 print {*STDOUT} $outdata;
50