简体   繁体   English

将十六进制数转换为二进制,并在Perl的末尾追加0

[英]Convert hex number to binary and append 0 at the end in Perl

I am trying to read a hex format file (32 bit) and convert each value to 33 bits by appending 0 to the LSB. 我试图读取十六进制格式文件(32位)并通过将0附加到LSB将每个值转换为33位。 For example 8000_0001 --> 1_0000_0002 . 例如8000_0001 - > 1_0000_0002

I tried this program and other ways but couldn't add 0 at the end of converted binary format number. 我尝试了这个程序和其他方法,但无法在转换后的二进制格式编号末尾添加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";

  #}
}

You can just use the left-shift operator, << . 你可以使用左移运算符<< But if you are running a 32-bit Perl then you have to divide the integer into two sixteen-bit chunks and shift them separately. 但是如果你运行的是32位Perl,那么你必须将整数分成两个16位的块并分别移动它们。

It isn't at all clear, but as far as I can tell your input file has a single hex value per line. 它一点也不清楚,但据我所知,您的输入文件每行有一个十六进制值。

Using this input file as sram1.hex 将此输入文件用作sram1.hex

11111111
abcdef01
23456789
BCDEF012
3456789A
Cdef0123
456789Ab
def01234
56789abc
ef012345
6789abcd
89abcdef
01234567
cdef0123
456789ab

This program seems to do what you ask. 这个程序似乎做你要求的。

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;
}

output 产量

022222222
1579BDE02
0468ACF12
179BDE024
068ACF134
19BDE0246
08ACF1356
1BDE02468
0ACF13578
1DE02468A
0CF13579A
113579BDE
002468ACE
19BDE0246
08ACF1356

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM