Francisco Delgado
Francisco Delgado

Reputation: 21

Convert Hex to Binary and keep leading 0's Perl

I have an array of hex numbers that I'd like to convert to binary numbers, the problem is, in my code it removes the leading 0's for things like 0,1,2,3. I need these leading 0's to process in a future section of my code. Is there an easy way to convert Hex to Binary and keep my leading 0's in perl?

use strict;
use warnings;
my @binary;
my @hex = ('ABCD', '0132', '2211');
foreach my $h(@hex){
my $bin = sprintf( "%b", hex($h));
push @binary, $bin;
}

foreach (@binary){
print "$_\n";
}

running the code gives me 1010101111001101 100110010 10001000010001

Edit: Found a similar answer using pack and unpack, replaced

sprint( "%b", hex($h)); with unpack( 'B*', pack('H*' ($h))

Upvotes: 1

Views: 2450

Answers (2)

ikegami
ikegami

Reputation: 386706

This solution uses the length of the hex repesentation to determine the length of the binary representation:

for my $num_hex (@nums_hex) {
   my $num = hex($num_hex);
   my $num_bin = sprintf('%0*b', length($num_hex)*4, $num);
   ...
}

Upvotes: 1

Chris Turner
Chris Turner

Reputation: 8142

You can specify the width of the output in sprintf or printf by putting the number between the % and the format character like this.

printf "%16b\n",hex("0132");

and by preceding the number with 0, make it pad the result with 0s like this

printf "%016b\n",hex("0132");

the latter giving the result of

0000000100110010

But this is all covered in the documentation for those functions.

Upvotes: 5

Related Questions