1f960902beffd56f49ae1a378e69b6018cd0adc2
[openwrt/staging/stintel.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
18 my $indata;
19
20 {
21 local $/;
22 my $fh;
23
24 if (@ARGV) {
25 open($fh, '<:raw', $ARGV[0]) || die("Unable to open $ARGV[0]: $!\n");
26 } else {
27 $fh = \*STDIN;
28 }
29
30 $indata = readline $fh;
31
32 close $fh;
33 }
34
35 my $len_data = length($indata);
36 my $num_digits_per_line = 12;
37 my $var_name;
38 my $outdata;
39
40 # Use the variable name of the file we read from, converting '/' and '.
41 # to '_', or, if this is stdin, just use "stdin" as the name.
42 if (@ARGV) {
43 $var_name = $ARGV[0];
44 $var_name =~ s/\//_/g;
45 $var_name =~ s/\./_/g;
46 } else {
47 $var_name = "stdin";
48 }
49
50 $outdata .= "unsigned char $var_name\[] = {";
51
52 # trailing ',' is acceptable, so instead of duplicating the logic for
53 # just the last character, live with the extra ','.
54 for (my $key= 0; $key < $len_data; $key++) {
55 if ($key % $num_digits_per_line == 0) {
56 $outdata .= "\n\t";
57 }
58 $outdata .= sprintf("0x%.2x, ", ord(substr($indata, $key, 1)));
59 }
60
61 $outdata .= "\n};\nunsigned int $var_name\_len = $len_data;\n";
62
63 binmode STDOUT;
64 print {*STDOUT} $outdata;
65