2016 Update
This commit is contained in:
parent
948b86eafa
commit
dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions
|
|
@ -1,7 +1,16 @@
|
|||
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
|
||||
|
||||
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc. The decimal number 26 expressed in base 16 would be 1a, for example.
|
||||
|
||||
;Task:
|
||||
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base.
|
||||
|
||||
It should return a string containing the digits of the resulting number, without leading zeros except for the number '''0''' itself.
|
||||
|
||||
For the digits beyond 9, one should use the lowercase English alphabet, where the digit '''a''' = 9+1, '''b''' = a+1, etc.
|
||||
|
||||
For example: the decimal number '''26''' expressed in base '''16''' would be '''1a'''.
|
||||
|
||||
Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base.
|
||||
|
||||
The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
|
||||
<br><br>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,19 @@
|
|||
var baselist = "0123456789abcdefghijklmnopqrstuvwxyz", listbase = [];
|
||||
for(var i = 0; i < baselist.length; i++) listbase[baselist[i]] = i; // Generate baselist reverse
|
||||
function basechange(snumber, frombase, tobase)
|
||||
{
|
||||
var i, t, to = new Array(Math.ceil(snumber.length * Math.log(frombase) / Math.log(tobase))), accumulator;
|
||||
if(1 < frombase < baselist.length || 1 < tobase < baselist.length) console.error("Invalid or unsupported base!");
|
||||
while(snumber[0] == baselist[0] && snumber.length > 1) snumber = snumber.substr(1); // Remove leading zeros character
|
||||
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; t--)
|
||||
{
|
||||
accumulator += listbase[to[t] || 0];
|
||||
to[t] = baselist[(accumulator % tobase) || 0];
|
||||
accumulator = Math.floor(accumulator / tobase);
|
||||
}
|
||||
return to.join('');
|
||||
}
|
||||
console.log("Result:", basechange("zzzzzzzzzz", 36, 10));
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
// Tom Wu jsbn.js http://www-cs-students.stanford.edu/~tjw/jsbn/
|
||||
var baselist = "0123456789abcdefghijklmnopqrstuvwxyz", listbase = [];
|
||||
for(var i = 0; i < baselist.length; i++) listbase[baselist[i]] = i; // Generate baselist reverse
|
||||
function baseconvert(snumber, frombase, tobase) // String number in base X to string number in base Y, arbitrary length, base
|
||||
{
|
||||
var i, t, to, accum = new BigInteger(), inexp = new BigInteger('1', 10), tb = new BigInteger(),
|
||||
fb = new BigInteger(), tmp = new BigInteger();
|
||||
console.log("Number is", snumber, "in base", frombase, "to base", tobase, "result should be",
|
||||
frombase < 37 && tobase < 37 ? parseInt(snumber, frombase).toString(tobase) : 'too large');
|
||||
while(snumber[0] == baselist[0] && snumber.length > 1) snumber = snumber.substr(1); // Remove leading zeros
|
||||
tb.fromInt(tobase);
|
||||
fb.fromInt(frombase);
|
||||
for(i = snumber.length - 1, to = new Array(Math.ceil(snumber.length * Math.log(frombase) / Math.log(tobase))); i > -1; i--)
|
||||
{
|
||||
accum = inexp.clone();
|
||||
accum.dMultiply(listbase[snumber[i]]);
|
||||
for(t = to.length - 1; accum.compareTo(BigInteger.ZERO) > 0 || t >= 0; t--)
|
||||
{
|
||||
tmp.fromInt(listbase[to[t]] || 0);
|
||||
accum = accum.add(tmp);
|
||||
to[t] = baselist[accum.mod(tb).intValue()];
|
||||
accum = accum.divide(tb);
|
||||
}
|
||||
inexp = inexp.multiply(fb);
|
||||
}
|
||||
while(to[0] == baselist[0] && to.length > 1) to = to.slice(1); // Remove leading zeros
|
||||
return to.join('');
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
function dec2base (base, n)
|
||||
local result, digit = ""
|
||||
while n > 0 do
|
||||
digit = n % base
|
||||
if digit > 9 then digit = string.char(digit + 87) end
|
||||
n = math.floor(n / base)
|
||||
result = digit .. result
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
local x = dec2base(16, 26)
|
||||
print(x) --> 1a
|
||||
print(tonumber(x, 16)) --> 26
|
||||
|
|
@ -10,7 +10,7 @@ toBase(n,b)={
|
|||
fromBase(s,b)={
|
||||
my(t=0);
|
||||
s=Vecsmall(s);
|
||||
forstep(i=#s,1,-1,
|
||||
for(i=1,#s,1,
|
||||
t=b*t+s[i]-if(s[i]<58,48,87)
|
||||
);
|
||||
t
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
use POSIX;
|
||||
|
||||
my ($num, $n_unparsed) = strtol('1a', 16);
|
||||
$n_unparsed == 0 or die "invalid characters found";
|
||||
print "$num\n"; # prints "26"
|
||||
sub to2 { sprintf "%b", shift; }
|
||||
sub to16 { sprintf "%x", shift; }
|
||||
sub from2 { unpack("N", pack("B32", substr("0" x 32 . shift, -32))); }
|
||||
sub from16 { hex(shift); }
|
||||
|
|
|
|||
|
|
@ -1,14 +1,17 @@
|
|||
sub digitize
|
||||
# Converts an integer to a single digit.
|
||||
{my $i = shift;
|
||||
$i < 10
|
||||
? $i
|
||||
: ('a' .. 'z')[$i - 10];}
|
||||
|
||||
sub to_base
|
||||
{my ($int, $radix) = @_;
|
||||
my $numeral = '';
|
||||
do {
|
||||
$numeral .= digitize($int % $radix);
|
||||
} while $int = int($int / $radix);
|
||||
scalar reverse $numeral;}
|
||||
sub base_to {
|
||||
my($n,$b) = @_;
|
||||
my $s = "";
|
||||
while ($n) {
|
||||
$s .= ('0'..'9','a'..'z')[$n % $b];
|
||||
$n = int($n/$b);
|
||||
}
|
||||
scalar(reverse($s));
|
||||
}
|
||||
sub base_from {
|
||||
my($n,$b) = @_;
|
||||
my $t = 0;
|
||||
for my $c (split(//, lc($n))) {
|
||||
$t = $b * $t + index("0123456789abcdefghijklmnopqrstuvwxyz", $c);
|
||||
}
|
||||
$t;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
use Math::BaseCnv 'cnv';
|
||||
print cnv("1a", 16, 10),"\n"; # "1a" from hex to decimal prints 26
|
||||
print lc(cnv(26, 10, 16)),"\n"; # 26 from decimal to hex prints "1a"
|
||||
use POSIX;
|
||||
my ($num, $n_unparsed) = strtol('1a', 16);
|
||||
$n_unparsed == 0 or die "invalid characters found";
|
||||
print "$num\n"; # prints "26"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,5 @@
|
|||
use ntheory qw/fromdigits todigitstring/;
|
||||
my $n = 65261;
|
||||
my $n16 = todigitstring($n, 16) || 0;
|
||||
my $n10 = fromdigits($n16, 16);
|
||||
say "$n $n16 $n10"; # prints "65261 feed 65261"
|
||||
|
|
@ -1,37 +1,37 @@
|
|||
/*REXX pgm converts integers from one base to another (base 2 ──► 90). */
|
||||
@abc = 'abcdefghijklmnopqrstuvwxyz' /*the lowercase (Latin) alphabet.*/
|
||||
parse upper var @abc @abcU /*uppercase a version of @abc. */
|
||||
@@ = 0123456789 || @abc || @abcU /*prefix 'em with numeric digits.*/
|
||||
@@ = @@'<>[]{}()?~!@#$%^&*_=|\/;:¢¬≈' /*add some special chars as well.*/
|
||||
/* [↑] all chars must be viewable*/
|
||||
numeric digits 3000 /*what da hey, support gihugeics.*/
|
||||
maxB=length(@@) /*max base (radix) supported here*/
|
||||
parse arg x toB inB 1 ox . 1 sigX 2 x2 . /*get: 3 args, origX, sign···*/
|
||||
if pos(sigX,"+-")\==0 then x=x2 /*Does X have a leading sign? */
|
||||
else sigX= /*Nope. No leading sign for X. */
|
||||
if x=='' then call erm /*if no X number, issue error.*/
|
||||
if toB=='' | toB=="," then toB=10 /*if skipped, assume default (10)*/
|
||||
if inB=='' | inB=="," then inB=10 /* " " " " " */
|
||||
if inB<2 | inb>maxB | \datatype(inB,'W') then call erb 'inBase ' inB
|
||||
if toB<2 | toB>maxB | \datatype(toB,'W') then call erb 'toBase ' toB
|
||||
#=0 /*result of converted X (base 10)*/
|
||||
do j=1 for length(x) /*convert X, base inB ──► base 10*/
|
||||
?=substr(x,j,1) /*pick off a numeral/digit from X*/
|
||||
_=pos(?, @@) /*calculate this numeral's value.*/
|
||||
if _==0 | _>inB then call erd x /*_ character an illegal numeral?*/
|
||||
#=#*inB+_-1 /*build a new number, dig by dig.*/
|
||||
end /*j*/ /* [↑] this also verifies digits*/
|
||||
y= /*the value of X in base B. */
|
||||
do while # >= toB /*convert #, base 10 ──► base toB*/
|
||||
y=substr(@@, (#//toB)+1, 1)y /*construct the output number. */
|
||||
#=#%toB /*··· and whittle # down also. */
|
||||
end /*while*/ /* [↑] process leaves a residual*/
|
||||
/* [↓] Y is the residual*/
|
||||
y=sigX || substr(@@, #+1, 1)y /*prepend the sign if it existed.*/
|
||||
say ox "(base" inB')' center('is',20) y "(base" toB')'
|
||||
exit /*stick a fork in it, we're done.*/
|
||||
/*──────────────────────────────────one─liner subroutines───────────────*/
|
||||
erb: call ser 'illegal' arg(1)", it must be in the range: 2──►"maxB
|
||||
erd: call ser 'illegal digit/numeral ['?"] in: " x
|
||||
erm: call ser 'no argument specified.'
|
||||
ser: say; say '***error!***'; say arg(1); exit 13
|
||||
/*REXX program converts integers from one base to another (using bases 2 ──► 90). */
|
||||
@abc = 'abcdefghijklmnopqrstuvwxyz' /*lowercase (Latin or English) alphabet*/
|
||||
parse upper var @abc @abcU /*uppercase a version of @abc. */
|
||||
@@ = 0123456789 || @abc || @abcU /*prefix them with all numeric digits. */
|
||||
@@ = @@'<>[]{}()?~!@#$%^&*_=|\/;:¢¬≈' /*add some special characters as well. */
|
||||
/* [↑] all characters must be viewable*/
|
||||
numeric digits 3000 /*what da hey, support gihugeic numbers*/
|
||||
maxB=length(@@) /*max base/radix supported in this code*/
|
||||
parse arg x toB inB 1 ox . 1 sigX 2 x2 . /*obtain: three args, origX, sign ··· */
|
||||
if pos(sigX, "+-")\==0 then x=x2 /*does X have a leading sign (+ or -) ?*/
|
||||
else sigX= /*Nope. No leading sign for the X value*/
|
||||
if x=='' then call erm /*if no X number, issue an error msg.*/
|
||||
if toB=='' | toB=="," then toB=10 /*if skipped, assume the default (10). */
|
||||
if inB=='' | inB=="," then inB=10 /* " " " " " " */
|
||||
if inB<2 | inB>maxB | \datatype(inB,'W') then call erb "inBase " inB
|
||||
if toB<2 | toB>maxB | \datatype(toB,'W') then call erb "toBase " toB
|
||||
#=0 /*result of converted X (in base 10).*/
|
||||
do j=1 for length(x) /*convert X: base inB ──► base 10. */
|
||||
?=substr(x,j,1) /*pick off a numeral/digit from X. */
|
||||
_=pos(?, @@) /*calculate the value of this numeral. */
|
||||
if _==0 | _>inB then call erd x /*is _ character an illegal numeral? */
|
||||
#=#*inB+_-1 /*build a new number, digit by digit. */
|
||||
end /*j*/ /* [↑] this also verifies digits. */
|
||||
y= /*the value of X in base B. */
|
||||
do while # >= toB /*convert #: base 10 ──► base toB.*/
|
||||
y=substr(@@, (#//toB)+1, 1)y /*construct the output number. */
|
||||
#=#%toB /* ··· and whittle # down also. */
|
||||
end /*while*/ /* [↑] algorithm may leave a residual.*/
|
||||
/* [↓] Y is the residual. */
|
||||
y=sigX || substr(@@, #+1, 1)y /*prepend the sign if it existed. */
|
||||
say ox "(base" inB')' center("is",20) y '(base' toB")"
|
||||
exit /*stick a fork in it, we're all done. */
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
erb: call ser 'illegal' arg(1)", it must be in the range: 2──►"maxB
|
||||
erd: call ser 'illegal digit/numeral ['?"] in: " x
|
||||
erm: call ser 'no argument specified.'
|
||||
ser: say; say '***error!***'; say arg(1); exit 13
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue