Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Base10 to Base2. (or "Why I don't like this SoPW")

by charnos (Friar)
on Oct 21, 2002 at 18:57 UTC ( [id://206901]=note: print w/replies, xml ) Need Help??


in reply to Base10 to Base2.

This *does* smell like homework, firstly. My apologies if it is not, but the hurried, incomplete description and the egregious disuse of builtin functions to perform (then) trivial calculations is suspicious. This question really isn't necessarily a Perl question either, but a general engineering question, since you're not making use of Perl's rich library of functions. There are functions not including those two which do aid tasks like this though, in the case of my example/answer, map.
my ($acc,$digit_count,$dec_string); $digit_count = 1; $dec_string = "1101110"; map {$acc += $_*$digit_count;$digit_count *=2;} reverse split '',$dec_ +string; print $acc;
This simply splits a decimal string into a list of characters, then reverses them to preserve order. The map statement is performed on all values in the list in order: the list moves leftward, incrementing by powers of 2, and adding the increment counter to an accumulator variable if the current digit is 1. This doesn't perform any checking however, you asked how to convert from decimal to binary, and this does it. Any non-zero-or-one value will *work*, but will not produce the expected value.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2024-04-16 05:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found