Non-decimal radices/Convert: Difference between revisions

m (Corrected alphabetical page ordering)
Line 1,283:
//optional special case for hex:
i = +('0x'+s) //hexadecimal base 16, if s='1a' then i=26.</lang>
 
=={{header|JavaScript}}==
<lang javascript>// Limitation: Any base or number that causes accumulator to overflow javascript value will lose precision!!
function basechange(snumber, frombase, tobase) // String number in base X to string number in base Y, arbitrary length, base
{
var i, t, to = new Array(Math.ceil(snumber.length * Math.log(frombase) / Math.log(tobase))), accumulator,
baselist = "0123456789abcdefghijklmnopqrstuvwxyz", listbase = [];
if(1 < frombase < baselist.length || 1 < tobase < baselist.length) console.error("Invalid or unsupported base!");
for(i = 0; i < baselist.length; i++) listbase[baselist[i]] = i; // Generate baselist reverse
while(snumber[0] == baselist[0] && snumber.length > 1) snumber = snumber.substr(1); // Remove leading zeros (note, zero can be any character, thus testing zero entry for baselist), do not strip all zeros!
console.log("Number is", snumber, "in base", frombase, "to base", tobase, "result should be", parseInt(snumber, frombase).toString(tobase));
for(i = snumber.length - 1, inexp = 1; i > -1; i--, inexp *= frombase)
for(accumulator = listbase[snumber[i]] * inexp, t = to.length - 1; accumulator > 0 || t >= 0; to[t--] = baselist[(accumulator % tobase) || 0], accumulator = Math.floor(accumulator / tobase))
accumulator += listbase[to[t] || 0];
return to.join('');
}
console.log("Result:", basechange("zzzzzzzzzz", 36, 10));</lang>
 
=={{header|jq}}==