I have a $test with 32 bit binary number.
$test = 00000000011111000000010111100100
How can i get the hexadecimal number for this.
Dear Deepu,
First of all, when you specify an integer literal that starts with
a zero, Perl interprets that as an octal number. For example, setting
$x to 0755 will set it to the decimal value of 493 (which is not the
same number as 755).
So you probably want to use the following line instead where the
binary number is quoted (so Perl won't assume it's in octal):
$test = "00000000011111000000010111100100";
or better yet, use the "0b" prefix to let Perl know you're specifying
a binary number:
$test = 0b00000000_01111100_00000101_11100100;
(This method allows you to put in optional underscores to make it
easier to read the bits.)
If you use the first approach, you can extract a hexadecimal string
like this:
my $test = "00000000011111000000010111100100";
my $value = oct("0b$test"); # converts to numerical value
my $hexString = sprintf('%x', $value);
The second approach is even easier, as the "0b" prefix lets Perl
know exactly what the number is supposed to be (so we don't have to
use a step to convert it to a numerical value):
my $test = 0b00000000_01111100_00000101_11100100;
my $hexString = sprintf('%x', $test);
Both these approaches set $hexString to "7c05e4". If for some
reason you want the leading zeros (so that you have "007c05e4"), then
change '%x' to '%08x'.
I hope this helps, Deepu.
-- Jean-Luc