2
0

bin2mif.pl 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/usr/bin/perl
  2. use strict;
  3. use integer;
  4. my($infile,$outfile,$depth,$width,$stride) = @ARGV;
  5. $stride = 1 unless (defined($stride));
  6. my $bytesperword = ($width+7) >> 3;
  7. open(my $in, '<:raw', $infile) or die;
  8. my $data;
  9. my $dlen = read($in,$data,$depth*$bytesperword*$stride);
  10. close($in);
  11. my $sdig = 1;
  12. while ((1 << ($sdig*4)) < $stride) {
  13. $sdig++;
  14. }
  15. my $adig = 1;
  16. while ((1 << ($adig*4)) < $depth) {
  17. $adig++;
  18. }
  19. for (my $s = 0; $s < $stride; $s++) {
  20. my $ofname = $outfile;
  21. if ($stride > 1) {
  22. $outfile =~ /^(.*?)(\.\w+)?$/;
  23. $ofname = sprintf("%s.%d%s", $1, $s, $2);
  24. }
  25. open(my $out, '>', $ofname) or die;
  26. printf $out "-- generated from %s\n", $infile;
  27. if ($stride > 1) {
  28. printf $out "-- array %d/%d (hex %0${sdig}X of [%0${sdig}X..%0${sdig}X])\n",
  29. $s+1, $stride, $s, 0, $stride-1;
  30. }
  31. printf $out "DEPTH = %d;\n", $depth;
  32. printf $out "WIDTH = %d;\n", $width;
  33. printf $out "ADDRESS_RADIX = HEX;\n";
  34. printf $out "DATA_RADIX = HEX;\n";
  35. printf $out "CONTENT BEGIN\n";
  36. my $addr;
  37. for ($addr = 0; $addr < $depth; $addr++) {
  38. my $offs = ($addr*$stride+$s)*$bytesperword;
  39. last if ($offs >= $dlen);
  40. printf $out "%0${adig}X : ", $addr;
  41. # Emitting data byte by byte avoids need for bigint
  42. for (my $b = $bytesperword-1; $b >= 0; $b--) {
  43. if ($offs+$b < $dlen) {
  44. printf $out "%02X", unpack("C", substr($data,$offs+$b,1));
  45. }
  46. }
  47. printf $out ";\n";
  48. }
  49. if ($addr < $depth) {
  50. printf $out "[%0${adig}X..%0${adig}X] : 00;\n", $addr, $depth-1;
  51. }
  52. printf $out "END;\n";
  53. close($out);
  54. }
  55. if ($stride > 1) {
  56. # Create an empty file for the benefit of make
  57. open(my $out, '>', $outfile) or die;
  58. close($out);
  59. }
  60. exit 0;