tags:

views:

3011

answers:

4

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

+16  A: 

`

sub bin2dec {
    return unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
}
Ed Guiness
+1 - I came here to say to use pack and unpack but you beat me to it.
Paul Tomblin
Every tool I ask tells me that 111111111111111111111111111111111 translates to 8589934591. Just how sure are you that 42949672958589934591 is correct?
innaM
This is done by the built-in oct() too, although it's a pretty poor name for it.
brian d foy
+14  A: 

Actually, I posted this for my reference and so I can point people to it when I'm asked. For reference, 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.)
Nathan Fellman
That is ... shocking. Thank you.
innaM
Fails for 111111111111111111111111111111111
Ed Guiness
@edg: that's to be expected on a 32 bit platform; works for me with 64 bits, albeit with a portability warning.
ysth
I always used pack, but I just benchmarked pack, oct, and Bit::Vector and this is by far the fastest of the three. It is 1449% faster than Bit::Vector and 316% faster than pack on my system.
gpojd
+10  A: 

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.

innaM
+3  A: 

Actually you can just stick '0b' on the front and it's treated as a binary number.

perl -le 'print 0b101'
5

But this only works for a bareword.

noswonky
Although this only works for a bare string.
noswonky