Anonymous user
Non-decimal radices/Convert: Difference between revisions
→{{header|REXX}}: added comments, added whitespace, changed some comments, added support for a leading sign. -- ~~~~
(→{{header|Perl 6}}: note that Int is a subtype of Real in Perl 6) |
(→{{header|REXX}}: added comments, added whitespace, changed some comments, added support for a leading sign. -- ~~~~) |
||
Line 1,244:
Instead of writing two seperate routines, only one was written to handle both tasks.
<br><br>This routine was ripped out from a bigger version of mine that allowed any number as input, including decimal (or whatever base) fractions.
<lang rexx>/*REXX program converts numbers from one base to another, from 2
/*┌────────────────────────────────────────────────────────────────────┐
┌─┘ Input to this program
│ │
│ x
│ toBase the base to convert X to. │
│ inBase the base X is expressed in. │
│ │
│
└─┐ of 10 to be used. The limits of
└────────────────────────────────────────────────────────────────────┘*/
@abc='abcdefghijklmnopqrstuvwxyz' /*
@abcU=@abc; upper @abcU
@@@=0123456789||@abc||@abcU /*prefix 'em with numeric digits.*/
@@@=@@@'<>[]{}()?~!@#$%^&*_
/*spec. chars should be viewable.*/
numeric digits 1000 /*what the hey, support gihugeics*/
maxB=length(@@@) /*max base (radix) supported here*/
parse arg x toB inB
if toB=='' | toB==',' then toB=10 /*if skipped, assume default (10)*/
if inB=='' | inB==',' then inB=10 /* " " " " " */
Line 1,268:
if toB<2 | tob>maxB then call erb 'toBase',toB /*bad boy toBase.*/
if x=='' then call erm /*bad boy number.*/
sigX=left(x,1); if pos(sigX,"-+")\==0 then x=substr(x,2) /*X has sign?*/
else sigX= /*no sign. */
_=substr(x,j,1) /*pick off a "digit" from X. */
v=pos(_,@@@) /*get the value of this "digits".*/
if v==0 |v>inB then call erd x,j,inB /*illegal "digit"? */
#=#*inB+v-1 /*construct new num, dig by dig. */
end /*j*/
y=; do while #>=toB /*convert #, base 10 ──► base toB*/
#=#%toB /*... and whittle # down also. */
end /*while #>-toB*/
y=sigX || substr(@@@,#+1,1)y
say
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────error subroutines───────────────────*/
erd: call ser; say 'illegal "digit" in' x":" _; call erx
erx: say; exit 13
'''output''' when input is (maximum positive integer in a signed 32-bit word): <tt> 7fffffff , 16 </tt>
<pre style="
7fffffff (base 16) is 2147483647 (base 10)
</pre>
'''output''' when input is: <tt> 4095 2 </tt>
<pre style="
4095 (base 10) is 111111111111 (base 2)
</pre>
'''output''' when input is: <tt> 100 3 2 </tt>
<pre style="
100 (base
</pre>
'''output''' when input is: <tt> zombieseatingdeadvegatables 10 36 </tt>
<pre style="
zombieseatingdeadvegatbles (base 36) is 28842619147225718605337632731806510179876 (base 10)
</pre>
|