tasks a-s
This commit is contained in:
parent
47bf37c096
commit
b83f433714
12433 changed files with 156208 additions and 123 deletions
7
Task/Non-decimal-radices-Convert/0DESCRIPTION
Normal file
7
Task/Non-decimal-radices-Convert/0DESCRIPTION
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
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.
|
||||
|
||||
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.
|
||||
2
Task/Non-decimal-radices-Convert/1META.yaml
Normal file
2
Task/Non-decimal-radices-Convert/1META.yaml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
---
|
||||
note: Arithmetic operations
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
(defun digit-value (chr)
|
||||
(cond ((and (char>= chr #\0)
|
||||
(char<= chr #\9))
|
||||
(- (char-code chr) (char-code #\0)))
|
||||
((and (char>= chr #\A)
|
||||
(char<= chr #\Z))
|
||||
(+ (- (char-code chr) (char-code #\A)) 10))
|
||||
((and (char>= chr #\a)
|
||||
(char<= chr #\z))
|
||||
(+ (- (char-code chr) (char-code #\a)) 10))))
|
||||
|
||||
(defun value-digit (n)
|
||||
(if (< n 10)
|
||||
(code-char (+ n (char-code #\0)))
|
||||
(code-char (+ (- n 10) (char-code #\A)))))
|
||||
|
||||
(defun num-from-cs (cs base)
|
||||
(if (endp cs)
|
||||
0
|
||||
(+ (digit-value (first cs))
|
||||
(* base (num-from-cs (rest cs) base)))))
|
||||
|
||||
(defun parse-num (str base)
|
||||
(num-from-cs (reverse (coerce str 'list)) base))
|
||||
|
||||
(include-book "arithmetic-3/top" :dir :system)
|
||||
|
||||
(defun num-to-cs (num base)
|
||||
(if (or (zp num) (zp base) (= base 1))
|
||||
nil
|
||||
(cons (value-digit (mod num base))
|
||||
(num-to-cs (floor num base) base))))
|
||||
|
||||
(defun show-num (num base)
|
||||
(coerce (reverse (num-to-cs num base)) 'string))
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
INT base = 16, from dec = 26;
|
||||
BITS to bits;
|
||||
|
||||
FORMAT hex repr = $n(base)r2d$;
|
||||
|
||||
FILE f; STRING str;
|
||||
|
||||
associate(f, str);
|
||||
putf(f, (hex repr, BIN from dec));
|
||||
print(("Hex: ",str, new line));
|
||||
|
||||
reset(f);
|
||||
getf(f, (hex repr, to bits));
|
||||
print(("Int: ",ABS to bits, new line))
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
STRING numeric alpha = "0123456789abcdefghijklmnopqrstuvwxyz";
|
||||
|
||||
PROC raise value error = ([]STRING args)VOID: (
|
||||
put(stand error, "Value error");
|
||||
STRING sep := ": ";
|
||||
FOR index TO UPB args - 1 DO put(stand error, (sep, args[index])); sep:=", " OD;
|
||||
new line(stand error);
|
||||
stop
|
||||
);
|
||||
|
||||
PROC base n = (INT num, base)STRING: (
|
||||
PROC base n = (INT num, base)STRING:
|
||||
( num = 0 | "" | base n(num OVER base, base) + numeric alpha[@0][num MOD base]);
|
||||
( num = 0 | "0" |: num > 0 | base n(num, base) | "-" + base n(-num, base) )
|
||||
);
|
||||
|
||||
PROC unsigned int = (STRING repr, INT base)INT:
|
||||
IF UPB repr < LWB repr THEN 0 ELSE
|
||||
INT pos;
|
||||
IF NOT char in string(repr[UPB repr], pos, numeric alpha) THEN
|
||||
raise value error("CHAR """+repr[UPB repr]+""" not valid")
|
||||
FI;
|
||||
unsigned int(repr[:UPB repr-1], base) * base + pos - 1
|
||||
FI
|
||||
;
|
||||
|
||||
PROC int = (STRING repr, INT base)INT:
|
||||
( repr[LWB repr]="-" | -unsigned int(repr[LWB repr + 1:], base) | unsigned int(repr, base) );
|
||||
|
||||
[]INT test = (-256, -255, -26, -25, 0, 25, 26, 255, 256);
|
||||
FOR index TO UPB test DO
|
||||
INT k = test[index];
|
||||
STRING s = base n(k,16); # returns the string 1a #
|
||||
INT i = int(s,16); # returns the integer 26 #
|
||||
print((k," => ", s, " => ", i, new line))
|
||||
OD
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
function strtol(str, base)
|
||||
{
|
||||
symbols = "0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
res = 0
|
||||
str = tolower(str)
|
||||
for(i=1; i < length(str); i++) {
|
||||
res += index(symbols, substr(str, i, 1)) - 1
|
||||
res *= base
|
||||
}
|
||||
res += index(symbols, substr(str, length(str), 1)) - 1
|
||||
return res
|
||||
}
|
||||
|
||||
function ltostr(num, base)
|
||||
{
|
||||
symbols = "0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
res = ""
|
||||
do {
|
||||
res = substr(symbols, num%base + 1, 1) res
|
||||
num = int(num/base)
|
||||
} while ( num != 0 )
|
||||
return res
|
||||
}
|
||||
|
||||
BEGIN {
|
||||
print strtol("7b", 16)
|
||||
print ltostr(123, 16)
|
||||
}
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
with Ada.Text_Io; use Ada.Text_Io;
|
||||
with Ada.Strings.Fixed;
|
||||
With Ada.Strings.Unbounded;
|
||||
|
||||
procedure Number_Base_Conversion is
|
||||
Max_Base : constant := 36;
|
||||
subtype Base_Type is Integer range 2..Max_Base;
|
||||
Num_Digits : constant String := "0123456789abcdefghijklmnopqrstuvwxyz";
|
||||
Invalid_Digit : exception;
|
||||
|
||||
function To_Decimal(Value : String; Base : Base_Type) return Integer is
|
||||
use Ada.Strings.Fixed;
|
||||
Result : Integer := 0;
|
||||
Decimal_Value : Integer;
|
||||
Radix_Offset : Natural := 0;
|
||||
begin
|
||||
for I in reverse Value'range loop
|
||||
Decimal_Value := Index(Num_Digits, Value(I..I)) - 1;
|
||||
if Decimal_Value < 0 then
|
||||
raise Invalid_Digit;
|
||||
end if;
|
||||
Result := Result + (Base**Radix_Offset * Decimal_Value);
|
||||
Radix_Offset := Radix_Offset + 1;
|
||||
end loop;
|
||||
return Result;
|
||||
end To_Decimal;
|
||||
|
||||
function To_Base(Value : Natural; Base : Base_Type) return String is
|
||||
use Ada.Strings.Unbounded;
|
||||
Result : Unbounded_String := Null_Unbounded_String;
|
||||
Temp : Natural := Value;
|
||||
Base_Digit : String(1..1);
|
||||
begin
|
||||
if Temp = 0 then
|
||||
return "0";
|
||||
end if;
|
||||
while Temp > 0 loop
|
||||
Base_Digit(1) := Num_Digits((Temp mod Base) + 1);
|
||||
if Result = Null_Unbounded_String then
|
||||
Append(Result, Base_Digit);
|
||||
else
|
||||
Insert(Source => Result,
|
||||
Before => 1,
|
||||
New_Item => Base_Digit);
|
||||
end if;
|
||||
Temp := Temp / Base;
|
||||
end loop;
|
||||
return To_String(Result);
|
||||
end To_Base;
|
||||
|
||||
begin
|
||||
Put_Line("26 converted to base 16 is " & To_Base(26, 16));
|
||||
Put_line("1a (base 16) is decimal" & Integer'image(To_Decimal("1a", 16)));
|
||||
end Number_Base_Conversion;
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
MsgBox % number2base(200, 16) ; 12
|
||||
MsgBox % parse(200, 16) ; 512
|
||||
|
||||
number2base(number, base)
|
||||
{
|
||||
While, base < digit := floor(number / base)
|
||||
{
|
||||
result := mod(number, base) . result
|
||||
number := digit
|
||||
}
|
||||
result := digit . result
|
||||
Return result
|
||||
}
|
||||
|
||||
parse(number, base)
|
||||
{
|
||||
result = 0
|
||||
pos := StrLen(number) - 1
|
||||
Loop, Parse, number
|
||||
{
|
||||
result := ((base ** pos) * A_LoopField) + result
|
||||
base -= 1
|
||||
}
|
||||
Return result
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
MsgBox % ToBase(29,3)
|
||||
MsgBox % ToBase(255,16)
|
||||
|
||||
MsgBox % FromBase("100",8)
|
||||
MsgBox % FromBase("ff",16)
|
||||
|
||||
ToBase(n,b) { ; n >= 0, 1 < b <= 36
|
||||
Return (n < b ? "" : ToBase(n//b,b)) . ((d:=mod(n,b)) < 10 ? d : Chr(d+87))
|
||||
}
|
||||
|
||||
FromBase(s,b) { ; convert base b number s=strings of 0..9,a..z, to AHK number
|
||||
Return (L:=StrLen(s))=0 ? "":(L>1 ? FromBase(SubStr(s,1,L-1),b)*b:0) + ((c:=Asc(SubStr(s,0)))>57 ? c-87:c-48)
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
PRINT " 0 (decimal) -> " FNtobase(0, 16) " (base 16)"
|
||||
PRINT " 26 (decimal) -> " FNtobase(26, 16) " (base 16)"
|
||||
PRINT "383 (decimal) -> " FNtobase(383, 16) " (base 16)"
|
||||
PRINT " 26 (decimal) -> " FNtobase(26, 2) " (base 2)"
|
||||
PRINT "383 (decimal) -> " FNtobase(383, 2) " (base 2)"
|
||||
PRINT " 1a (base 16) -> " ;FNfrombase("1a", 16) " (decimal)"
|
||||
PRINT " 1A (base 16) -> " ;FNfrombase("1A", 16) " (decimal)"
|
||||
PRINT "17f (base 16) -> " ;FNfrombase("17f", 16) " (decimal)"
|
||||
PRINT "101111111 (base 2) -> " ;FNfrombase("101111111", 2) " (decimal)"
|
||||
END
|
||||
|
||||
DEF FNtobase(N%, B%)
|
||||
LOCAL D%,A$
|
||||
REPEAT
|
||||
D% = N% MOD B%
|
||||
N% DIV= B%
|
||||
A$ = CHR$(48 + D% - 39*(D%>9)) + A$
|
||||
UNTIL N% = FALSE
|
||||
=A$
|
||||
|
||||
DEF FNfrombase(A$, B%)
|
||||
LOCAL N%
|
||||
REPEAT
|
||||
N% *= B%
|
||||
N% += ASC(A$) - 48 + 7*(ASCA$>64) + 32*(ASCA$>96)
|
||||
A$ = MID$(A$,2)
|
||||
UNTIL A$ = ""
|
||||
= N%
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
( display
|
||||
=
|
||||
. !arg:<10
|
||||
| !arg:<36&chr$(asc$a+!arg+-10)
|
||||
| "Base too big"
|
||||
)
|
||||
& ( base
|
||||
= n b
|
||||
. !arg:(?n.?b)
|
||||
& !n:<!b
|
||||
& ( !n:~<0&display$!n
|
||||
| NOTSUPPORTED
|
||||
)
|
||||
| base$(div$(!n.!b).!b) display$(mod$(!n.!b))
|
||||
)
|
||||
& whl
|
||||
' ( put
|
||||
$ "Enter non-negative integer in decimal notation (or something else to stop):"
|
||||
& get':~/#>-1:?n
|
||||
& put$"Enter base (less than 37):"
|
||||
& get$:~/#>1:~>36:?b
|
||||
& out$(!n " in base " !b " is " str$(base$(!n.!b)))
|
||||
);
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
#include <string>
|
||||
#include <cstdlib>
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
|
||||
std::string const digits = "0123456789abcdefghijklmnopqrstuvwxyz";
|
||||
|
||||
std::string to_base(unsigned long num, int base)
|
||||
{
|
||||
if (num == 0)
|
||||
return "0";
|
||||
|
||||
std::string result;
|
||||
while (num > 0) {
|
||||
std::ldiv_t temp = std::div(num, (long)base);
|
||||
result += digits[temp.rem];
|
||||
num = temp.quot;
|
||||
}
|
||||
std::reverse(result.begin(), result.end());
|
||||
return result;
|
||||
}
|
||||
|
||||
unsigned long from_base(std::string const& num_str, int base)
|
||||
{
|
||||
unsigned long result = 0;
|
||||
for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)
|
||||
result = result * base + digits.find(num_str[pos]);
|
||||
return result;
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
|
||||
char *to_base(int64_t num, int base)
|
||||
{
|
||||
char *tbl = "0123456789abcdefghijklmnopqrstuvwxyz";
|
||||
char buf[66] = {'\0'};
|
||||
char *out;
|
||||
uint64_t n;
|
||||
int i, len = 0, neg = 0;
|
||||
if (base > 36) {
|
||||
fprintf(stderr, "base %d too large\n", base);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* safe against most negative integer */
|
||||
n = ((neg = num < 0)) ? (~num) + 1 : num;
|
||||
|
||||
do { buf[len++] = tbl[n % base]; } while(n /= base);
|
||||
|
||||
out = malloc(len + neg + 1);
|
||||
for (i = neg; len > 0; i++) out[i] = buf[--len];
|
||||
if (neg) out[0] = '-';
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
long from_base(const char *num_str, int base)
|
||||
{
|
||||
char *endptr;
|
||||
/* there is also strtoul() for parsing into an unsigned long */
|
||||
/* in C99, there is also strtoll() and strtoull() for parsing into long long and
|
||||
* unsigned long long, respectively */
|
||||
int result = strtol(num_str, &endptr, base);
|
||||
return result;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int64_t x;
|
||||
x = ~(1LL << 63) + 1;
|
||||
printf("%lld in base 2: %s\n", x, to_base(x, 2));
|
||||
x = 383;
|
||||
printf("%lld in base 16: %s\n", x, to_base(x, 16));
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
Class Utils.Number [ Abstract ]
|
||||
{
|
||||
|
||||
ClassMethod ConvertBase10ToN(pNum As %Integer = "", pBase As %Integer = "", pBaseStr As %String = "", pPos As %Integer = 0) As %String
|
||||
{
|
||||
If pNum=0 Quit ""
|
||||
Set str=..ConvertBase10ToN(pNum\pBase, pBase, pBaseStr, pPos+1)
|
||||
Quit str_$Extract(pBaseStr, pNum#pBase+1)
|
||||
}
|
||||
|
||||
ClassMethod ConvertBaseNTo10(pStr As %String = "", pBase As %Integer = "", pBaseStr As %String = "", pPos As %Integer = 0) As %Integer
|
||||
{
|
||||
If pStr="" Quit 0
|
||||
Set num=..ConvertBaseNTo10($Extract(pStr, 1, *-1), pBase, pBaseStr, pPos+1)
|
||||
Set dec=$Find(pBaseStr, $Extract(pStr, *))-2
|
||||
Quit num+(dec*(pBase**pPos))
|
||||
}
|
||||
|
||||
ClassMethod ConvertBase(pStr As %String = "", pFrom As %Integer = 10, pTo As %Integer = 10, pBaseStr As %String = "", pLen As %Integer = 0) As %String
|
||||
{
|
||||
// some initialisation
|
||||
If pBaseStr="" Set pBaseStr="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
||||
|
||||
// check input values
|
||||
If pFrom=10 Set pStr=$Number(pStr, "i", 0) If pStr="" Quit ""
|
||||
Set pFrom=$Number(pFrom, "i", 2, 94) If pFrom="" Quit ""
|
||||
Set pTo=$Number(pTo, "i", 2, 94) If pTo="" Quit ""
|
||||
Set pLen=$Number(pLen, "i", 0, 32) If pLen="" Quit ""
|
||||
|
||||
// does base number exceed base string?
|
||||
If pFrom>$Length(pBaseStr) Quit ""
|
||||
If pTo>$Length(pBaseStr) Quit ""
|
||||
|
||||
// allow for upper/lowercase values
|
||||
If pTo=10 {
|
||||
If $Match(pStr, "^[0-9a-z]+$"), $Match($Extract(pBaseStr, 1, pFrom), "^[0-9A-Z]+$") {
|
||||
Set pStr=$ZConvert(pStr, "U")
|
||||
}
|
||||
If $Match(pStr, "^[0-9A-Z]+$"), $Match($Extract(pBaseStr, 1, pFrom), "^[0-9a-z]+$") {
|
||||
Set pStr=$ZConvert(pStr, "L")
|
||||
}
|
||||
}
|
||||
|
||||
// do the conversion
|
||||
If pFrom=pTo {
|
||||
Set pStr=pStr
|
||||
} ElseIf pFrom=10 {
|
||||
Set pStr=..ConvertBase10ToN($Select(pStr=0: "", 1: pStr), pTo, pBaseStr)
|
||||
} ElseIf pTo=10 {
|
||||
Set pStr=..ConvertBaseNTo10(pStr, pFrom, pBaseStr)
|
||||
} Else {
|
||||
Set pStr=..ConvertBase10ToN(..ConvertBaseNTo10(pStr, pFrom, pBaseStr), pTo, pBaseStr)
|
||||
}
|
||||
|
||||
// return value
|
||||
If pLen=0 Quit pStr
|
||||
If pTo'=10 Quit ..PadStr(pStr, pLen, $Extract(pBaseStr))
|
||||
Quit ..PadStr(pStr, pLen)
|
||||
}
|
||||
|
||||
ClassMethod PadStr(pStr As %String, pLen As %Integer, pZero As %String = 0) As %String [ Private ]
|
||||
{
|
||||
If $Length(pStr)>pLen Quit pStr
|
||||
Quit $Translate($Justify(pStr, pLen), " ", pZero)
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
(parse-integer "1a" :radix 16) ; returns multiple values: 26, 2
|
||||
(write-to-string 26 :base 16) ; also "1A"
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
import std.stdio, std.conv, std.string;
|
||||
|
||||
void main() {
|
||||
"1abcd".to!int(16).writeln();
|
||||
|
||||
toLower(60_272_032_366.to!string(36) ~ " " ~
|
||||
591_458.to!string(36)).writeln();
|
||||
}
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
import std.stdio, std.array, std.ascii;
|
||||
|
||||
enum string mDigits = "0123456789abcdefghijklmnopqrstuvwxyz";
|
||||
|
||||
ulong atoiRadix(in string str, in int radix=10, int* consumed=null) {
|
||||
static int dtoi(in char dc, in int radix) {
|
||||
static int[immutable char] digit;
|
||||
immutable char d = cast(char)toLower(dc);
|
||||
if (digit.length == 0) // not init yet
|
||||
foreach (i, c; mDigits)
|
||||
digit[c] = i;
|
||||
if (radix > 1 && radix <= digit.length &&
|
||||
d in digit && digit[d] < radix)
|
||||
return digit[d];
|
||||
return int.min; // a negative for error.
|
||||
}
|
||||
|
||||
ulong result;
|
||||
int sp;
|
||||
for (; sp < str.length; sp++) {
|
||||
immutable int d = dtoi(str[sp], radix);
|
||||
if (d >= 0) // valid digit char
|
||||
result = radix * result + d;
|
||||
else
|
||||
break;
|
||||
}
|
||||
if (sp != str.length) // some char in str not converted.
|
||||
sp = -sp;
|
||||
if (consumed !is null) // signal error if not positive.
|
||||
*consumed = sp;
|
||||
return result;
|
||||
}
|
||||
|
||||
string itoaRadix(ulong num, in int radix=10) pure nothrow
|
||||
in {
|
||||
assert(radix > 1 && radix <= mDigits.length);
|
||||
} body {
|
||||
string result;
|
||||
while (num > 0) {
|
||||
//immutable int d = num % radix;
|
||||
immutable int d = cast(int)(num % radix);
|
||||
result = mDigits[d] ~ result;
|
||||
num = (num - d) / radix;
|
||||
}
|
||||
return result.empty ? "0" : result;
|
||||
}
|
||||
|
||||
void main() {
|
||||
immutable string numStr = "1ABcdxyz???";
|
||||
|
||||
int ate;
|
||||
writef("'%s' (base %d) = %d", numStr, 16,
|
||||
atoiRadix(numStr, 16, &ate));
|
||||
|
||||
if (ate <= 0)
|
||||
writefln("\tConverted only: '%s'", numStr[0 .. -ate]);
|
||||
else
|
||||
writeln();
|
||||
|
||||
writeln(itoaRadix(60_272_032_366, 36), " ",
|
||||
itoaRadix(591_458, 36));
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
def stringToInteger := __makeInt
|
||||
def integerToString(i :int, base :int) {
|
||||
return i.toString(base)
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
? stringToInteger("200", 16)
|
||||
# value: 512
|
||||
|
||||
? integerToString(200, 16)
|
||||
# value: "c8"
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
function to_base(integer i, integer base)
|
||||
integer rem
|
||||
sequence s
|
||||
s = ""
|
||||
while i > 0 do
|
||||
rem = remainder(i,base)
|
||||
if rem < 10 then
|
||||
s = prepend(s, '0'+rem)
|
||||
else
|
||||
s = prepend(s, 'a'-10+rem)
|
||||
end if
|
||||
i = floor(i/base)
|
||||
end while
|
||||
|
||||
if length(s) = 0 then
|
||||
s = "0"
|
||||
end if
|
||||
|
||||
return s
|
||||
end function
|
||||
|
||||
function from_base(sequence s, integer base)
|
||||
integer i,d
|
||||
i = 0
|
||||
for n = 1 to length(s) do
|
||||
i *= base
|
||||
if s[n] >= '0' and s[n] <= '9' then
|
||||
d = s[n]-'0'
|
||||
elsif s[n] >= 'a' then
|
||||
d = s[n]-'a'+10
|
||||
end if
|
||||
i += d
|
||||
end for
|
||||
return i
|
||||
end function
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
USE: math.parser
|
||||
|
||||
12345 16 >base .
|
||||
"3039" 16 base> .
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
42 dup
|
||||
2 base !
|
||||
. \ 101010
|
||||
hex
|
||||
. \ 2A
|
||||
decimal
|
||||
|
|
@ -0,0 +1 @@
|
|||
$ff . \ 255
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
MODULE Conversion
|
||||
IMPLICIT NONE
|
||||
CHARACTER(36) :: alphanum = "0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
|
||||
CONTAINS
|
||||
|
||||
FUNCTION ToDecimal(base, instr)
|
||||
INTEGER :: ToDecimal
|
||||
INTEGER :: length, i, n, base
|
||||
CHARACTER(*) :: instr
|
||||
|
||||
ToDecimal = 0
|
||||
length = LEN(instr)
|
||||
DO i = 1, length
|
||||
n = INDEX(alphanum, instr(i:i)) - 1
|
||||
n = n * base**(length-i)
|
||||
Todecimal = ToDecimal + n
|
||||
END DO
|
||||
END FUNCTION ToDecimal
|
||||
|
||||
FUNCTION ToBase(base, number)
|
||||
CHARACTER(31) :: ToBase
|
||||
INTEGER :: base, number, i, rem
|
||||
|
||||
ToBase = " "
|
||||
DO i = 31, 1, -1
|
||||
IF(number < base) THEN
|
||||
ToBase(i:i) = alphanum(number+1:number+1)
|
||||
EXIT
|
||||
END IF
|
||||
rem = MOD(number, base)
|
||||
ToBase(i:i) = alphanum(rem+1:rem+1)
|
||||
number = number / base
|
||||
END DO
|
||||
ToBase = ADJUSTL(ToBase)
|
||||
END FUNCTION ToBase
|
||||
|
||||
END MODULE Conversion
|
||||
|
||||
PROGRAM Base_Convert
|
||||
USE Conversion
|
||||
|
||||
WRITE (*,*) ToDecimal(16, "1a")
|
||||
WRITE (*,*) ToBase(16, 26)
|
||||
|
||||
END PROGRAM
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func main () {
|
||||
s := strconv.FormatInt(26, 16) // returns the string "1a"
|
||||
fmt.Println(s)
|
||||
|
||||
i, err := strconv.ParseInt("1a", 16, 64) // returns the integer (int64) 26
|
||||
if err == nil {
|
||||
fmt.Println(i)
|
||||
}
|
||||
b, ok := new(big.Int).SetString("1a", 16) // returns the big integer 26
|
||||
if ok {
|
||||
fmt.Println(b)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
def radixParse = { s, radix -> Integer.parseInt(s, radix) }
|
||||
def radixFormat = { i, radix -> Integer.toString(i, radix) }
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
def numString = '101'
|
||||
(2..Character.MAX_RADIX).each { radix ->
|
||||
def value = radixParse(numString, radix)
|
||||
assert value == radix**2 + 1
|
||||
printf (" %3s (%2d) == %4d (10)\n", numString, radix, value)
|
||||
|
||||
def valM2str = radixFormat(value - 2, radix)
|
||||
def biggestDigit = radixFormat(radix - 1, radix)
|
||||
assert valM2str == biggestDigit + biggestDigit
|
||||
printf ("%3s (%2d) - 2 (10) == %4s (%2d)\n", numString, radix, valM2str, radix)
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
Prelude> Numeric.showIntAtBase 16 Char.intToDigit 42 ""
|
||||
"2a"
|
||||
Prelude> fst $ head $ Numeric.readInt 16 Char.isHexDigit Char.digitToInt "2a"
|
||||
42
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
import Data.List
|
||||
import Data.Char
|
||||
|
||||
toBase :: Int -> Int -> [Int]
|
||||
toBase b v = toBase' [] v where
|
||||
toBase' a 0 = a
|
||||
toBase' a v = toBase' (r:a) q where (q,r) = v `divMod` b
|
||||
|
||||
fromBase :: Int -> [Int] -> Int
|
||||
fromBase b ds = foldl' (\n k -> n * b + k) 0 ds
|
||||
|
||||
toAlphaDigits :: [Int] -> String
|
||||
toAlphaDigits = map convert where
|
||||
convert n | n < 10 = chr (n + ord '0')
|
||||
| otherwise = chr (n + ord 'a' - 10)
|
||||
|
||||
fromAlphaDigits :: String -> [Int]
|
||||
fromAlphaDigits = map convert where
|
||||
convert c | isDigit c = ord c - ord '0'
|
||||
| isUpper c = ord c - ord 'A' + 10
|
||||
| isLower c = ord c - ord 'a' + 10
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
*Main> toAlphaDigits $ toBase 16 $ 42
|
||||
"2a"
|
||||
*Main> fromBase 16 $ fromAlphaDigits $ "2a"
|
||||
42
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
CHARACTER txt*80
|
||||
|
||||
num = 36^7 -1 ! 7836416410
|
||||
CALL DecToBase(num, txt, 36)
|
||||
WRITE(ClipBoard, Name) num, txt, BaseToDec(36, txt)
|
||||
END
|
||||
|
||||
FUNCTION BaseToDec(base, string)
|
||||
CHARACTER string
|
||||
BaseToDec = 0
|
||||
length = LEN_TRIM(string)
|
||||
DO i = 1, length
|
||||
n = INDEX("0123456789abcdefghijklmnopqrstuvwxyz", string(i)) - 1
|
||||
BaseToDec = BaseToDec + n * base^(length-i)
|
||||
ENDDO
|
||||
END
|
||||
|
||||
SUBROUTINE DectoBase(decimal, string, base)
|
||||
CHARACTER string
|
||||
string = '0'
|
||||
temp = decimal
|
||||
length = CEILING( LOG(decimal+1, base) )
|
||||
DO i = length, 1, -1
|
||||
n = MOD( temp, base )
|
||||
string(i) = "0123456789abcdefghijklmnopqrstuvwxyz"(n+1)
|
||||
temp = INT(temp / base)
|
||||
ENDDO
|
||||
END
|
||||
|
|
@ -0,0 +1 @@
|
|||
num=7836416410; txt=zzzzzzz; 7836416410;
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
procedure main()
|
||||
every ( ns := "16r5a" | "-12r1a" ) &
|
||||
( b := 8 | 12 | 16 ) do {
|
||||
ns2 := convert(n := numeric(ns),b)
|
||||
printf("ns=%s -> n=%d -> %s\n",ns,n,ns2)
|
||||
}
|
||||
end
|
||||
|
||||
link printf
|
||||
|
||||
procedure convert(i,b) #: convert i to base b radix representation
|
||||
static digits
|
||||
initial digits := &digits || &lcase
|
||||
|
||||
i := integer(i) | runerr(101, i) # arg/error checking
|
||||
/b := 10 | ( 2 < (b := integer(b)) <= *digits ) | runerr(205,b)
|
||||
|
||||
if b = 10 then return i
|
||||
else {
|
||||
p := (s := "", (i := -(0 > i),"-")|"") || b || "r" # prefix/setup
|
||||
until i = 0 & *s > 0 do
|
||||
s ||:= digits[1 + 1( i % b, i /:= b)]
|
||||
|
||||
return p || reverse(s)
|
||||
}
|
||||
end
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
2b100 8b100 10b_100 16b100 36b100 36bzy
|
||||
4 64 _100 256 1296 1294
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
numerals=: '0123456789abcdefghijklmnopqrstuvwxyz'
|
||||
baseNtoL=: numerals {~ #.inv
|
||||
baseLtoN=: [ #. numerals i. ]
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
2 baseNtoL 100 101
|
||||
1100100
|
||||
1100101
|
||||
16 baseNtoL 26
|
||||
1a
|
||||
36 baseLtoN 'zy'
|
||||
1294
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
base=: baseNtoL :: baseLtoN
|
||||
|
||||
16 base 'aa'
|
||||
170
|
||||
16 base 170
|
||||
aa
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
public static long backToTen(String num, int oldBase){
|
||||
return Long.parseLong(num, oldBase); //takes both uppercase and lowercase letters
|
||||
}
|
||||
|
||||
public static String tenToBase(long num, int newBase){
|
||||
return Long.toString(num, newBase);//add .toUpperCase() for capital letters
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
public static BigInteger backToTenBig(String num, int oldBase){
|
||||
return new BigInteger(num, oldBase); //takes both uppercase and lowercase letters
|
||||
}
|
||||
|
||||
public static String tenBigToBase(BigInteger num, int newBase){
|
||||
return num.toString(newBase);//add .toUpperCase() for capital letters
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
k = 26
|
||||
s = k.toString(16) //gives 1a
|
||||
i = parseInt('1a',16) //gives 26
|
||||
//optional special case for hex:
|
||||
i = +('0x'+s) //hexadecimal base 16, if s='1a' then i=26.
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
' Base Converter v6
|
||||
|
||||
global alphanum$
|
||||
alphanum$ ="0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
|
||||
for i =1 to 20
|
||||
RandNum = int( 100 *rnd( 1))
|
||||
base =2 +int( 35 *rnd( 1))
|
||||
|
||||
print "Decimal "; using( "###", RandNum); " to base "; using( "###", base);_
|
||||
" is "; toBase$( base, RandNum),_
|
||||
" back to dec. "; toDecimal( base, toBase$( base, RandNum))
|
||||
next i
|
||||
|
||||
end ' ___________________________________________________________
|
||||
|
||||
function toBase$( base, number) ' Convert decimal variable to number string.
|
||||
toBase$ =""
|
||||
for i =10 to 1 step -1
|
||||
remainder =number mod base
|
||||
toBase$ =mid$( alphanum$, remainder +1, 1) +toBase$
|
||||
number =int( number /base)
|
||||
if number <1 then exit for
|
||||
next i
|
||||
end function
|
||||
|
||||
function toDecimal( base, s$) ' Convert number string to decimal variable.
|
||||
toDecimal =0
|
||||
for i =1 to len( s$)
|
||||
toDecimal =toDecimal *base +instr( alphanum$, mid$( s$, i, 1), 1) -1
|
||||
next i
|
||||
end function
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
eval(26,16)
|
||||
define(`frombase',`eval(0r$2:$1)')
|
||||
frombase(1a,16)
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
IntegerString[26,16]
|
||||
FromDigits["1a", 16])
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
/* NetRexx */
|
||||
options replace format comments java crossref symbols nobinary
|
||||
|
||||
import java.math.BigInteger
|
||||
|
||||
numeric digits 200
|
||||
|
||||
parse arg input -- input should be val, radix; no input results in using default test data
|
||||
-- test data - number pairs where 1st is value and 2nd is target radix
|
||||
inputs = [ -
|
||||
'1234, 10', '01234, 8', 'fe, 16', 'f0e, 16', -
|
||||
'0, 10', '00, 2', '11, 2', '070, 8', -
|
||||
'77, 8', 'f0e, 16', '070, 16', '0xf0e, 36', -
|
||||
'000999ABCXYZ, 36', 'ff, 36', 'f, 16', 'z, 37' -
|
||||
]
|
||||
if input.length() > 0 then inputs = [input] -- replace test data with user input
|
||||
|
||||
loop i_ = 0 to inputs.length - 1
|
||||
do
|
||||
in = inputs[i_]
|
||||
parse in val . ',' radix .
|
||||
valB = toDecimal(val, radix) -- NetRexx default is to store digits as Rexx strings
|
||||
valD = fromDecimal(valB + 0, radix) -- Add zero just to prove the result treated as a number
|
||||
say val.right(16)'['radix.right(2, 0)']:' valB.right(16)'[10] ==' valD.right(16)'['radix.right(2, 0)']'
|
||||
catch nx = NumberFormatException
|
||||
say 'Error -- Input:' val', radix:' radix
|
||||
nx.printStackTrace()
|
||||
end
|
||||
end i_
|
||||
|
||||
return
|
||||
|
||||
method toDecimal(val = String, radix = int 10) public static returns Rexx
|
||||
bi = BigInteger(val, radix)
|
||||
return bi.toString()
|
||||
|
||||
method fromDecimal(val = String, radix = int 10) public static returns Rexx
|
||||
bi = BigInteger(val.toString(), 10)
|
||||
return bi.toString(radix)
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
let int_of_basen n str =
|
||||
match n with
|
||||
| 16 -> int_of_string("0x" ^ str)
|
||||
| 2 -> int_of_string("0b" ^ str)
|
||||
| 8 -> int_of_string("0o" ^ str)
|
||||
| _ -> failwith "unhandled"
|
||||
|
||||
let basen_of_int n d =
|
||||
match n with
|
||||
| 16 -> Printf.sprintf "%x" d
|
||||
| 8 -> Printf.sprintf "%o" d
|
||||
| _ -> failwith "unhandled"
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
let to_base b v =
|
||||
let rec to_base' a v =
|
||||
if v = 0 then
|
||||
a
|
||||
else
|
||||
to_base' (v mod b :: a) (v / b)
|
||||
in
|
||||
to_base' [] v
|
||||
|
||||
let from_base b ds =
|
||||
List.fold_left (fun n k -> n * b + k) 0 ds
|
||||
|
||||
let to_alpha_digit n =
|
||||
if n < 10 then
|
||||
char_of_int (n + int_of_char '0')
|
||||
else
|
||||
char_of_int (n + int_of_char 'a' - 10)
|
||||
|
||||
let to_alpha_digits ds =
|
||||
let buf = Buffer.create (List.length ds) in
|
||||
List.iter (fun i -> Buffer.add_char buf (to_alpha_digit i)) ds;
|
||||
Buffer.contents buf
|
||||
|
||||
let from_alpha_digit c = match c with
|
||||
'0'..'9' -> int_of_char c - int_of_char '0'
|
||||
| 'A'..'Z' -> int_of_char c - int_of_char 'A' + 10
|
||||
| 'a'..'z' -> int_of_char c - int_of_char 'a' + 10
|
||||
|
||||
let from_alpha_digits s =
|
||||
let result = ref [] in
|
||||
String.iter (fun c -> result := from_alpha_digit c :: !result) s;
|
||||
List.rev !result
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
toBase(n,b)={
|
||||
my(s="",t);
|
||||
while(n,
|
||||
t=n%b;
|
||||
n\=b;
|
||||
s=Str(if(t<=9,t,Strchr(Vecsmall([87+t]))),s)
|
||||
);
|
||||
if(#s,s,"0")
|
||||
};
|
||||
fromBase(s,b)={
|
||||
my(t=0);
|
||||
s=Vecsmall(s);
|
||||
forstep(i=#s,1,-1,
|
||||
t=b*t+s[i]-if(s[i]<58,48,87)
|
||||
);
|
||||
t
|
||||
};
|
||||
|
|
@ -0,0 +1 @@
|
|||
base_convert("26", 10, 16); // returns "1a"
|
||||
|
|
@ -0,0 +1 @@
|
|||
intval("1a", 16); // returns 26
|
||||
|
|
@ -0,0 +1 @@
|
|||
base_convert(26, 10, 16); // returns "1a"
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
// converts int to binary string
|
||||
decbin(26); // returns "11010"
|
||||
// converts int to octal string
|
||||
decoct(26); // returns "32"
|
||||
// converts int to hex string
|
||||
dechex(26); // returns "1a"
|
||||
// converts binary string to int
|
||||
bindec("11010"); // returns 26
|
||||
// converts octal string to int
|
||||
octdec("32"); // returns 26
|
||||
// converts hex string to int
|
||||
hexdec("1a"); // returns 26
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
convert: procedure (N, base) returns (character (64) varying) recursive;
|
||||
declare N fixed binary (31), base fixed binary;
|
||||
declare table (0:15) character (
|
||||
'0', '1', '2', '3', '4', '5', '6', '7',
|
||||
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
|
||||
declare s character (64) varying;
|
||||
|
||||
if N = 0 then return ('');
|
||||
|
||||
s = convert(N/base, base);
|
||||
return (s || table(mod(N, base)) );
|
||||
end convert;
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
Program ConvertDemo(output);
|
||||
|
||||
uses
|
||||
Math, SysUtils;
|
||||
|
||||
const
|
||||
alphanum = '0123456789abcdefghijklmnopqrstuvwxyz';
|
||||
|
||||
function ToDecimal(base: integer; instring: string): integer;
|
||||
var
|
||||
inlength, i, n: integer;
|
||||
begin
|
||||
ToDecimal := 0;
|
||||
inlength := length(instring);
|
||||
for i := 1 to inlength do
|
||||
begin
|
||||
n := pos(instring[i], alphanum) - 1;
|
||||
n := n * base**(inlength-i);
|
||||
Todecimal := ToDecimal + n;
|
||||
end;
|
||||
end;
|
||||
|
||||
function ToBase(base, number: integer): string;
|
||||
var
|
||||
i, rem: integer;
|
||||
begin
|
||||
ToBase :=' ';
|
||||
for i := 31 downto 1 do
|
||||
begin
|
||||
if (number < base) then
|
||||
begin
|
||||
ToBase[i] := alphanum[number+1];
|
||||
break;
|
||||
end;
|
||||
rem := number mod base;
|
||||
ToBase[i] := alphanum[rem+1];
|
||||
number := number div base;
|
||||
end;
|
||||
ToBase := trimLeft(ToBase);
|
||||
end;
|
||||
|
||||
begin
|
||||
writeln ('1A: ', ToDecimal(16, '1a'));
|
||||
writeln ('26: ', ToBase(16, 26));
|
||||
end.
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
sub from-base(Str $str, Int $base) {
|
||||
+":$base\<$str>";
|
||||
}
|
||||
|
||||
sub to-base(Real $num, Int $base) {
|
||||
$num.base($base);
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
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,14 @@
|
|||
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;}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
(de numToString (N Base)
|
||||
(default Base 10)
|
||||
(let L NIL
|
||||
(loop
|
||||
(let C (% N Base)
|
||||
(and (> C 9) (inc 'C 39))
|
||||
(push 'L (char (+ C `(char "0")))) )
|
||||
(T (=0 (setq N (/ N Base)))) )
|
||||
(pack L) ) )
|
||||
|
||||
(de stringToNum (S Base)
|
||||
(default Base 10)
|
||||
(let N 0
|
||||
(for C (chop S)
|
||||
(when (> (setq C (- (char C) `(char "0"))) 9)
|
||||
(dec 'C 39) )
|
||||
(setq N (+ C (* N Base))) )
|
||||
N ) )
|
||||
|
||||
(prinl (numToString 26 16))
|
||||
(prinl (stringToNum "1a" 16))
|
||||
(prinl (numToString 123456789012345678901234567890 36))
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
define number_to_base(n, base);
|
||||
radix_apply(n, '%p', sprintf, base);
|
||||
enddefine;
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
define string_in_base_to_number(s, base);
|
||||
incharitem(stringin(base >< ':' >< s))();
|
||||
enddefine;
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
Global alphanum$ = "0123456789abcdefghijklmnopqrstuvwxyz" ;36 digits
|
||||
#maxIntegerBitSize = SizeOf(Integer) * 8
|
||||
|
||||
Procedure toDecimal(base, s.s)
|
||||
Protected length, i, toDecimal
|
||||
|
||||
length = Len(s)
|
||||
If length: toDecimal = FindString(alphanum$, Left(s, 1), 1) - 1: EndIf
|
||||
|
||||
For i = 2 To length
|
||||
toDecimal * base + FindString(alphanum$, Mid(s, i, 1), 1) - 1
|
||||
Next
|
||||
ProcedureReturn toDecimal
|
||||
EndProcedure
|
||||
|
||||
Procedure.s toBase(base, number)
|
||||
Protected i, rem, toBase.s{#maxIntegerBitSize} = Space(#maxIntegerBitSize)
|
||||
|
||||
For i = #maxIntegerBitSize To 1 Step -1
|
||||
rem = number % base
|
||||
PokeC(@toBase + i - 1, PeekC(@alphanum$ + rem))
|
||||
If number < base: Break: EndIf
|
||||
number / base
|
||||
Next
|
||||
ProcedureReturn LTrim(toBase)
|
||||
EndProcedure
|
||||
|
||||
If OpenConsole()
|
||||
PrintN( Str(toDecimal(16, "1a")) )
|
||||
|
||||
PrintN( toBase(16, 26) )
|
||||
|
||||
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
|
||||
Input()
|
||||
CloseConsole()
|
||||
EndIf
|
||||
|
|
@ -0,0 +1 @@
|
|||
i = int('1a',16) # returns the integer 26
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
def baseN(num,b):
|
||||
return (((num == 0) and "0" )
|
||||
or ( baseN(num // b, b).lstrip("0")
|
||||
+ digits[num % b]))
|
||||
|
||||
# alternatively:
|
||||
def baseN(num,b):
|
||||
if num == 0: return "0"
|
||||
result = ""
|
||||
while num != 0:
|
||||
num, d = divmod(num, b)
|
||||
result += digits[d]
|
||||
return result[::-1] # reverse
|
||||
|
||||
k = 26
|
||||
s = baseN(k,16) # returns the string 1a
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
/*REXX program converts numbers from one base to another, from 2 ──► 90.*/
|
||||
/*┌────────────────────────────────────────────────────────────────────┐
|
||||
┌─┘ Input to this program (bases must be positive whole numbers): └─┐
|
||||
│ │
|
||||
│ x is required (it may have a sign). │
|
||||
│ toBase the base to convert X to. │
|
||||
│ inBase the base X is expressed in. │
|
||||
│ │
|
||||
│ toBase or inBase can be a comma (,) which causes the default │
|
||||
└─┐ of 10 to be used. The limits of bases are: 2 ──► 90. ┌─┘
|
||||
└────────────────────────────────────────────────────────────────────┘*/
|
||||
@abc='abcdefghijklmnopqrstuvwxyz' /*lowercase Latin alphabet. */
|
||||
@abcU=@abc; upper @abcU /*go whole hog and extend 'em. */
|
||||
@@@=0123456789||@abc||@abcU /*prefix 'em with numeric digits.*/
|
||||
@@@=@@@'<>[]{}()?~!@#$%^&*_=|\/;:¢¬≈' /*add some special chars as well.*/
|
||||
/*special chars must be viewable.*/
|
||||
numeric digits 1000 /*what da hey, support gihugeics.*/
|
||||
maxB=length(@@@) /*max base (radix) supported here*/
|
||||
parse arg x toB inB 1 ox . /*get a number, toBase, inBase*/
|
||||
if toB=='' | toB==',' then toB=10 /*if skipped, assume default (10)*/
|
||||
if inB=='' | inB==',' then inB=10 /* " " " " " */
|
||||
if inB<2 | inb>maxB then call erb 'inBase',inB /*bad boy inBase.*/
|
||||
if toB<2 | tob>maxB then call erb 'toBase',toB /* " " toBase.*/
|
||||
if x=='' then call erm /* " " number.*/
|
||||
sigX=left(x,1); if pos(sigX,"-+")\==0 then x=substr(x,2) /*X has sign?*/
|
||||
else sigX= /*no sign. */
|
||||
#=0; do j=1 for length(x) /*convert X, base inB ──► base 10*/
|
||||
_=substr(x,j,1) /*pick off a "digit" from X. */
|
||||
v=pos(_,@@@) /*get the value of this "digit". */
|
||||
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*/
|
||||
y=substr(@@@,(#//toB)+1,1)y /*construct the output number. */
|
||||
#=#%toB /*... and whittle # down also. */
|
||||
end /*while #>-toB*/
|
||||
|
||||
y=sigX || substr(@@@,#+1,1)y /*prepend the sign if it existed.*/
|
||||
say ox "(base" inB')' center('is',20) y "(base" toB')' /*show & tell.*/
|
||||
exit /*stick a fork in it, we're done.*/
|
||||
/*──────────────────────────────────error subroutines───────────────────*/
|
||||
erb: call ser; say 'illegal' arg(2) "base:" arg(1) "must be in range: 2──►" maxB
|
||||
erd: call ser; say 'illegal "digit" in' x":" _
|
||||
erm: call ser; say 'no argument specified.'
|
||||
ser: say; say '*** error! ***'; say; exit 13
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
s = 26.to_s(16) # returns the string 1a
|
||||
i = '1a'.to_i(16) # returns the integer 26
|
||||
|
|
@ -0,0 +1 @@
|
|||
"59".to_i(7) # returns 5, but this is probably not what you wanted
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
module BaseConvert
|
||||
DIGITS = %w{0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z}
|
||||
|
||||
def baseconvert(str, basefrom, baseto)
|
||||
dec2base(base2dec(str, basefrom), baseto)
|
||||
end
|
||||
|
||||
def base2dec(str, base)
|
||||
raise ArgumentError, "base is invalid" unless base.between?(2, DIGITS.length)
|
||||
res = 0
|
||||
str.to_s.downcase.each_char do |c|
|
||||
idx = DIGITS[0,base].find_index(c)
|
||||
idx.nil? and raise ArgumentError, "invalid base-#{base} digit: #{c}"
|
||||
res = res * base + idx
|
||||
end
|
||||
res
|
||||
end
|
||||
|
||||
def dec2base(n, base)
|
||||
return "0" if n == 0
|
||||
raise ArgumentError, "base is invalid" unless base.between?(2, DIGITS.length)
|
||||
res = []
|
||||
while n > 0
|
||||
n, r = n.divmod(base)
|
||||
res.unshift(DIGITS[r])
|
||||
end
|
||||
res.join("")
|
||||
end
|
||||
end
|
||||
|
||||
include BaseConvert
|
||||
p baseconvert("107h", 23, 7) # => "50664"
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
global basCvt$
|
||||
basCvt$ ="0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
html "<table border=1><tr bgcolor=wheat align=center><td>Decimal</td><td>To Base</td><td>Num</td><td>to Dec</td></tr>"
|
||||
|
||||
for i =1 to 10
|
||||
RandNum = int(100 * rnd(1))
|
||||
base = 2 +int(35 * rnd(1))
|
||||
|
||||
html "<tr align=right><td>";using("###", RandNum);"</td><td>";using("###", base);"</td><td>";toBase$(base,RandNum);"</td><td>";toDecimal( base, toBase$( base, RandNum));"</td></tr>"
|
||||
next i
|
||||
html "</table>"
|
||||
end
|
||||
|
||||
function toBase$(b,n) ' b=base n=nmber
|
||||
toBase$ =""
|
||||
for i =10 to 1 step -1
|
||||
toBase$ =mid$(basCvt$,n mod b +1,1) +toBase$
|
||||
n =int( n /b)
|
||||
if n <1 then exit for
|
||||
next i
|
||||
end function
|
||||
|
||||
function toDecimal( b, s$) ' scring number to decimal
|
||||
toDecimal =0
|
||||
for i =1 to len( s$)
|
||||
toDecimal = toDecimal * b + instr(basCvt$,mid$(s$,i,1),1) -1
|
||||
next i
|
||||
end function
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
26 printString &radix: 16
|
||||
Integer readFrom: '1A' &radix: 16.
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
fun toBase b v = let
|
||||
fun toBase' (a, 0) = a
|
||||
| toBase' (a, v) = toBase' (v mod b :: a, v div b)
|
||||
in
|
||||
toBase' ([], v)
|
||||
end
|
||||
|
||||
fun fromBase b ds =
|
||||
foldl (fn (k, n) => n * b + k) 0 ds
|
||||
|
||||
val toAlphaDigits = let
|
||||
fun convert n = if n < 10 then chr (n + ord #"0")
|
||||
else chr (n + ord #"a" - 10)
|
||||
in
|
||||
implode o map convert
|
||||
end
|
||||
|
||||
val fromAlphaDigits = let
|
||||
fun convert c = if Char.isDigit c then ord c - ord #"0"
|
||||
else if Char.isUpper c then ord c - ord #"A" + 10
|
||||
else if Char.isLower c then ord c - ord #"a" + 10
|
||||
else raise Match
|
||||
in
|
||||
map convert o explode
|
||||
end
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
namespace eval baseconvert {
|
||||
variable chars "0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
namespace export baseconvert
|
||||
}
|
||||
proc baseconvert::dec2base {n b} {
|
||||
variable chars
|
||||
expr {$n == 0 ? 0
|
||||
: "[string trimleft [dec2base [expr {$n/$b}] $b] 0][string index $chars [expr {$n%$b}]]"
|
||||
}
|
||||
}
|
||||
proc baseconvert::base2dec {n b} {
|
||||
variable chars
|
||||
set sum 0
|
||||
foreach char [split $n ""] {
|
||||
set d [string first $char [string range $chars 0 [expr {$b - 1}]]]
|
||||
if {$d == -1} {error "invalid base-$b digit '$char' in $n"}
|
||||
set sum [expr {$sum * $b + $d}]
|
||||
}
|
||||
return $sum
|
||||
}
|
||||
proc baseconvert::baseconvert {n basefrom baseto} {
|
||||
dec2base [base2dec $n $basefrom] $baseto
|
||||
}
|
||||
|
||||
namespace import baseconvert::baseconvert
|
||||
baseconvert 12345 10 23 ;# ==> 107h
|
||||
baseconvert 107h 23 7 ;# ==> 50664
|
||||
baseconvert 50664 7 10 ;# ==> 12345
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
#import std
|
||||
#import nat
|
||||
|
||||
num_to_string "b" = ||'0'! (-: num digits--letters)*+ @NiX ~&r->l ^|rrPlCrlPX/~& division\"b"
|
||||
|
||||
string_to_num "b" = @x =>0 sum^|/(-:@rlXS num digits--letters) product/"b"
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
test_data = <1,2,15,32,100,65536,323498993>
|
||||
|
||||
#cast %sLnLUL
|
||||
|
||||
tests =
|
||||
|
||||
<
|
||||
num_to_string32* test_data,
|
||||
string_to_num32* num_to_string32* test_data,
|
||||
num_to_string8* test_data,
|
||||
string_to_num8* num_to_string8* test_data>
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
include c:\cxpl\codes; \intrinsic 'code' declarations
|
||||
string 0; \use zero-terminated string convention
|
||||
|
||||
func Num2Str(N, B); \Convert integer N to a numeric string in base B
|
||||
int N, B;
|
||||
char S(32); int I;
|
||||
[I:= 31;
|
||||
S(31):= 0; \terminate string
|
||||
repeat I:= I-1;
|
||||
N:= N/B;
|
||||
S(I):= rem(0) + (if rem(0)<=9 then ^0 else ^a-10);
|
||||
until N=0;
|
||||
return @S(I); \BEWARE! very temporary string space
|
||||
];
|
||||
|
||||
func Str2Num(S, B); \Convert numeric string S in base B to an integer
|
||||
char S; int B;
|
||||
int I, N;
|
||||
[I:= 0; N:= 0;
|
||||
while S(I) do
|
||||
[N:= N*B + S(I) - (if S(I)<=^9 then ^0 else ^a-10); I:= I+1];
|
||||
return N;
|
||||
];
|
||||
|
||||
[Text(0, Num2Str(0, 10)); CrLf(0);
|
||||
Text(0, Num2Str(26, 16)); CrLf(0);
|
||||
Text(0, Num2Str($7FFF_FFFF, 2)); CrLf(0);
|
||||
IntOut(0, Str2Num("0100", 2)); CrLf(0);
|
||||
IntOut(0, Str2Num("1a", 16)); CrLf(0);
|
||||
IntOut(0, Str2Num("deadbeef", 16)); CrLf(0);
|
||||
]
|
||||
Loading…
Add table
Add a link
Reference in a new issue