Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Reading Binary

by TomDLux (Vicar)
on Jun 15, 2011 at 16:38 UTC ( [id://909808]=note: print w/replies, xml ) Need Help??


in reply to Reading Binary

Given some input string representing a binary number, $bin, verify it only contains 1 & 0, to protect little Bobby Tables, then convert to an ordinary number. You only have 15 values to deal with, so you can hardcode an array. If it's 10 to 20 bits, you can precompute the array; if it's more, probably better to stick with calculating things as you need them, possibly with memoizing.

my @block = qw( D C CD B BD BC BCD A AD AC ACD AB ABD ABC ABCD ); unshift @block, ''; # empty string for 0 $bin =~ m{([01]+)}; # untaint input my $idx = eval "0b$1"; my $result = $block[$idx];

As Occam said: Entia non sunt multiplicanda praeter necessitatem.

Replies are listed 'Best First'.
Re^2: Reading Binary
by jwkrahn (Abbot) on Jun 15, 2011 at 20:47 UTC
    $bin =~ m{([01]+)}; # untaint input my $idx = eval "0b$1";

    1. You shouldn't use the results of a regular expression unless you verify that it matched correctly.
    2. Why use string eval when oct is less dangerous and provides the same result.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://909808]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-04-24 06:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found