3 # srecimage.pl - script to convert a binary image into srec
4 # Copyright (c) 2015 - Jo-Philipp Wich <jow@openwrt.org>
6 # This script is in the public domain.
10 my ($input, $output, $offset) = @ARGV;
12 if (!defined($input) || !-f $input || !defined($output) ||
13 !defined($offset) || $offset !~ /^(0x)?[a-fA-F0-9]+$/) {
14 die "Usage: $0 <input file> <output file> <load address>\n";
19 my ($type, $addr, $data, $len) = @_;
20 my @addrtypes = qw(%04X %04X %06X %08X %08X %04X %06X %08X %06X %04X);
21 my $addrstr = sprintf $addrtypes[$type], $addr;
23 $len = length($data) if ($len <= 0);
24 $len += 1 + (length($addrstr) / 2);
28 foreach my $byte (unpack('C*', pack('H*', $addrstr)), unpack('C*', $data))
33 return sprintf "S%d%02X%s%s%02X\r\n",
34 $type, $len, $addrstr, uc(unpack('H*', $data)), ~($sum & 0xFF) & 0xFF;
38 open(IN, '<:raw', $input) || die "Unable to open $input: $!\n";
39 open(OUT, '>:raw', $output) || die "Unable to open $output: $!\n";
41 my ($basename) = $output =~ m!([^/]+)$!;
43 print OUT srec(0, 0, $basename, 0);
45 my $off = hex($offset);
48 while (defined($len = read(IN, my $buf, 16)) && $len > 0)
50 print OUT srec(3, $off, $buf, $len);
54 print OUT srec(7, hex($offset), "", 0);