How can I convert the binary string $x_bin="0001001100101"
to its numeric value $x_num=613
in Perl?
Conversion of string to integer in Perl has many ways. One is to use Typecasting, while the other one involves use of 'sprintf' function. Sometimes people do not use the word casting in Perl because the whole thing of conversion is automatic.
my $x = 0; print qq("$x"); prints "0" .
To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .
My preferred way is:
$x_num = oct("0b" . $x_bin);
Quoting from man perlfunc
:
oct EXPR oct Interprets EXPR as an octal string and returns the corresponding value. (If EXPR happens to start off with "0x", interprets it as a hex string. If EXPR starts off with "0b", it is interpreted as a binary string. Leading whitespace is ignored in all three cases.)
sub bin2dec { return unpack("N", pack("B32", substr("0" x 32 . shift, -32))); }
As usual, there's is also an excellent CPAN module that should be mentioned here: Bit::Vector.
The transformation would look something like this:
use Bit::Vector;
my $v = Bit::Vector->new_Bin( 32, '0001001100101' );
print "hex: ", $v->to_Hex(), "\n";
print "dec: ", $v->to_Dec(), "\n";
The binary strings can be of almost any length and you can do other neat stuff like bit-shifting, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With