Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a binary string to a number in Perl?

Tags:

binary

perl

How can I convert the binary string $x_bin="0001001100101" to its numeric value $x_num=613 in Perl?

like image 681
Nathan Fellman Avatar asked Jan 27 '09 14:01

Nathan Fellman


People also ask

How do I convert between numbers and strings 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.

How do I convert 0 to string in Perl?

my $x = 0; print qq("$x"); prints "0" .

How do you convert a string to binary?

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


3 Answers

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.) 
like image 153
Nathan Fellman Avatar answered Sep 24 '22 18:09

Nathan Fellman


sub bin2dec {     return unpack("N", pack("B32", substr("0" x 32 . shift, -32))); } 
like image 42
Ed Guiness Avatar answered Sep 23 '22 18:09

Ed Guiness


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.

like image 21
innaM Avatar answered Sep 22 '22 18:09

innaM