Dharshana Eswaran wrote:
> Hi All,
Hello,
> My aim is to supply a hexadecimal value and print its binary value.
>
> I have written a small piece of code for the same:
>
> $input = 23; #any decimal value
> $hex1 = sprintf ("%x",$input);
> $binary = unpack 'B*', pack 'H*', $hex1;
> @fields1 = unpack 'A4A4', $binary;
> print "$fields1[1] $fields1[0]"; # i need to print the Lower Nibble
> first and then the Higher nibble
>
> Output:
> 0111 0010
I get a different output:
$ perl -le'
$input = 23;
$hex1 = sprintf "%x", $input;
$binary = unpack "B*", pack "H*", $hex1;
@fields1 = unpack "A4A4", $binary;
print "$fields1[1] $fields1[0]";
'
0111 0001
Perhaps you want something like this:
$ perl -le'
$input = 23;
printf "%04b %04b\n", $input & 15, $input >> 4;
'
0111 0001
> This works fine for any double digit number.
>
> But this logic does not work with single digit number as input. When i give
> a single digit number (for eg: 5) as input, it is stored as 01010000 in
> $binary variable instead of 00000101.
$ perl -le'
$input = 5;
printf "%08b\n", $input;
'
00000101
John
--
Perl isn't a toolbox, but a small machine shop where you can special-order
certain sorts of tools at low cost and in short order. -- Larry Wall
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/