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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.