简体   繁体   中英

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. For example 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.

%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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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