我正在尝试读取十六进制格式文件(32位),并通过将0附加到LSB将每个值转换为33位。例如8000_0001
- > 1_0000_0002
。
我尝试了这个程序和其他方法,但无法在转换后的二进制格式编号末尾添加0
。
%h2b = (
0 => "0000",
1 => "0001", 2 => "0010", 3 => "0011",
4 => "0100", 5 => "0101", 6 => "0110",
7 => "0111", 8 => "1000", 9 => "1001",
a => "1010", b => "1011", c => "1100",
d => "1101", e => "1110", f => "1111",
);
$hex = "4";
($binary = $hex) =~ s/(.)/$h2b{lc $1}/g;
open(INFILE1, "./sram1.hex") || die("$TESTLIST could not be found\n");
open(INFILE2, ">>sram2.hex") || die("$TESTLIST could not be found\n");
@testarray1 = <INFILE1>;
$test_count1 = @testarray1;
foreach $line (@testarray1) {
$hex = $line;
($binary = $hex) =~ s/(.)/$h2b{lc $1}/g;
print INFILE2 "$binary";
}
#close (INFILE2);
open(INFILE3, "./sram2.hex") || die("$TESTLIST could not be found\n");
open(INFILE4, ">>sram3.hex") || die("$TESTLIST could not be found\n");
@testarray2 = <INFILE3>;
foreach $line1 (@testarray2) {
my $int = unpack("N", pack("B32", substr("0" x 32 . $line1, -32)));
my $num = sprintf("%x", $int);
print INFILE4 "$num\n";
my $hexi = unpack('H4', $line1);
print "$hexi\n";
#}
}
答案 0 :(得分:2)
您可以使用左移运算符<<
。但是如果你运行的是32位Perl,那么你必须将整数分成两个16位的块并分别移动它们。
一点也不清楚,但据我所知,你的输入文件每行都有一个十六进制值。
将此输入文件用作sram1.hex
11111111
abcdef01
23456789
BCDEF012
3456789A
Cdef0123
456789Ab
def01234
56789abc
ef012345
6789abcd
89abcdef
01234567
cdef0123
456789ab
这个程序似乎按照你的要求行事。
use strict;
use warnings;
open my $in, '<', 'sram1.hex' or die $!;
open my $out, '>', 'sram3.hex' or die $!;
while (my $line = <$in>) {
chomp $line;
my $val = hex($line);
printf $out "%05X%04X\n", $val >> 15, ($val << 1) & 0xFFFF;
}
<强>输出强>
022222222
1579BDE02
0468ACF12
179BDE024
068ACF134
19BDE0246
08ACF1356
1BDE02468
0ACF13578
1DE02468A
0CF13579A
113579BDE
002468ACE
19BDE0246
08ACF1356