Non-decimal radices/Convert: Difference between revisions
Content added Content deleted
m (→{{header|REXX}}: made some cosmetic changes.) |
(Wrong code added--non functional) |
||
Line 1,283: | Line 1,283: | ||
//optional special case for hex: |
//optional special case for hex: |
||
i = +('0x'+s) //hexadecimal base 16, if s='1a' then i=26.</lang> |
i = +('0x'+s) //hexadecimal base 16, if s='1a' then i=26.</lang> |
||
Arbitrary base, length base conversion (note: only works with arrays of numbers; requires converting to/from base character) |
|||
<lang javascript> |
|||
function conv(farray, fbase, tbase) |
|||
{ // Takes a fbase chunk(s) until we have a tbase chunk, then removes tbase chunk(s) while possible, repeats for entire value |
|||
var res = [], accum = 0, rem = 0, pos, val, a, b, res; |
|||
for(a = 0, pos = farray.length - 1; a < farray.length; a++, pos--) // base x -> base 10 |
|||
if(farray[a] > 0 && farray[a] < fbase) accum += farray[a] * Math.pow(fbase, pos); |
|||
for(a = 1, val = Math.pow(tbase, pos); val <= accum; a++) |
|||
val = Math.pow(tbase, a); // Find max value that fits |
|||
for(a--; a >= 0; a--) |
|||
{ |
|||
val = Math.pow(tbase, a); |
|||
res[a] = Math.floor(accum / val); |
|||
accum %= val; |
|||
} |
|||
return res.reverse(); |
|||
}</lang> |
|||
=={{header|jq}}== |
=={{header|jq}}== |