Non-decimal radices/Convert: Difference between revisions

no edit summary
No edit summary
 
(187 intermediate revisions by 79 users not shown)
Line 1:
{{task|Arithmetic operations}}
{{task|Arithmetic operations}}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.
 
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>
 
=={{header|11l}}==
Converting from string to number:
<syntaxhighlight lang="11l">print(Int(‘1A’, radix' 16)) // prints the integer 26</syntaxhighlight>
 
Converting from number to string:
<syntaxhighlight lang="11l">print(String(26, radix' 16)) // prints ‘1A’</syntaxhighlight>
 
=={{header|8086 Assembly}}==
Be it a bug or otherwise "unintended" behavior, the <code>AAD</code> instruction, which was meant to convert unpacked binary-coded decimal values to hex to allow for division, has a "secret" operand that most assemblers did not support at the time. Typing <code>AAD</code> into your assembler would place the hex values <code>D5 0A</code> in your program. The <code>0A</code> (hexadecimal equivalent of decimal 10) actually represents the base, and can be used to convert between bases in a roundabout way. Unpacked binary-coded decimal (also known as ASCII binary coded decimal) only uses the bottom four bits of each byte, so for example a number like <code>0x0103</code> represents decimal 13.
 
<syntaxhighlight lang="asm">mov ah,02h
mov al,00h ;this is the unpacked encoding of octal "20" aka 10 in hexadecimal, 16 in decimal. Ignore the leading zeroes.
byte 0D5h,08h ;most assemblers don't allow you to encode a base so we have to inline the bytecode.</syntaxhighlight>
 
The result is that <code>AX</code> now equals <code>0x0010</code>.
 
The <code>AAM</code> instruction (ASCII Adjust for Multiplication) has a similar "feature." You'll need to inline the bytecode <code>D4 ??</code> where ?? is your desired base. These two can be used in combination to switch from hexadecimal to binary coded decimal without needing a lookup table or multiplication.
 
<syntaxhighlight lang="asm">mov ax,10h
aam
byte 0D5h,10h ;inlined bytecode for AAD using base 16</syntaxhighlight>
 
The result is that <code>AX = 0x0016</code>. This effectively lets us convert a hexadecimal value to one that "looks like" its decimal equivalent, albeit the logic only holds for 8-bit values. (This is a useful technique for printing numbers to the screen in decimal.)
 
=={{header|ACL2}}==
<syntaxhighlight lang="lisp">(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))</syntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">CHAR ARRAY digits="0123456789abcdefghijklmnopqrstuvwxyz"
 
PROC CheckBase(BYTE b)
IF b<2 OR b>digits(0) THEN
PrintE("Base is out of range!")
Break()
FI
RETURN
 
PROC Encode(CARD v BYTE b CHAR ARRAY s)
CARD d
BYTE i,len
CHAR tmp
 
CheckBase(b)
len=0
DO
d=v MOD b
len==+1
s(len)=digits(d+1)
v==/b
UNTIL v=0
OD
s(0)=len
 
FOR i=1 to len/2
DO
tmp=s(i)
s(i)=s(len-i+1)
s(len-i+1)=tmp
OD
RETURN
 
CARD FUNC Decode(CHAR ARRAY s BYTE b)
CARD res
BYTE i,j,found
 
CheckBase(b)
res=0
FOR i=1 TO s(0)
DO
found=0
FOR j=1 TO digits(0)
DO
IF digits(j)=s(i) THEN
found=1 EXIT
FI
OD
IF found=0 THEN
PrintE("Unrecognized character!")
Break()
FI
res==*b
res==+j-1
OD
RETURN (res)
 
PROC Main()
CARD v=[6502],v2
BYTE b
CHAR ARRAY s(256)
 
FOR b=2 TO 23
DO
Encode(v,b,s)
v2=Decode(s,b)
PrintF("%U -> base %B %S -> %U%E",v,b,s,v2)
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Non-decimal_radices_convert.png Screenshot from Atari 8-bit computer]
<pre>
6502 -> base 2 1100101100110 -> 6502
6502 -> base 3 22220211 -> 6502
6502 -> base 4 1211212 -> 6502
6502 -> base 5 202002 -> 6502
6502 -> base 6 50034 -> 6502
6502 -> base 7 24646 -> 6502
6502 -> base 8 14546 -> 6502
6502 -> base 9 8824 -> 6502
6502 -> base 10 6502 -> 6502
6502 -> base 11 4981 -> 6502
6502 -> base 12 391a -> 6502
6502 -> base 13 2c62 -> 6502
6502 -> base 14 2526 -> 6502
6502 -> base 15 1dd7 -> 6502
6502 -> base 16 1966 -> 6502
6502 -> base 17 1588 -> 6502
6502 -> base 18 1214 -> 6502
6502 -> base 19 i04 -> 6502
6502 -> base 20 g52 -> 6502
6502 -> base 21 efd -> 6502
6502 -> base 22 d9c -> 6502
6502 -> base 23 c6g -> 6502
</pre>
 
=={{header|Ada}}==
Ada provides built-in capability to convert between all bases from 2 through 16. This task requires conversion for bases up to 36. The following program demonstrates such a conversion using an iterative solution.
<langsyntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
with Ada.Strings.Fixed;
With Ada.Strings.Unbounded;
Line 62 ⟶ 231:
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;</langsyntaxhighlight>
 
=={{header|Aime}}==
<syntaxhighlight lang="aime">o_text(bfxa(0, 0, 16, 1000000));
o_byte('\n');
o_text(bfxa(0, 0, 5, 1000000));
o_byte('\n');
o_text(bfxa(0, 0, 2, 1000000));
o_byte('\n');
 
o_integer(alpha("f4240", 16));
o_byte('\n');
o_integer(alpha("224000000", 5));
o_byte('\n');
o_integer(alpha("11110100001001000000", 2));
o_byte('\n');</syntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 74 ⟶ 258:
a numbers base.
 
<langsyntaxhighlight lang="algol68">INT base = 16, from dec = 26;
BITS to bits;
 
Line 87 ⟶ 271:
reset(f);
getf(f, (hex repr, to bits));
print(("Int: ",ABS to bits, new line))</langsyntaxhighlight>
Output:
<pre>
Line 104 ⟶ 288:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<langsyntaxhighlight lang="algol68">STRING numeric alpha = "0123456789abcdefghijklmnopqrstuvwxyz";
 
PROC raise value error = ([]STRING args)VOID: (
Line 139 ⟶ 323:
INT i = int(s,16); # returns the integer 26 #
print((k," => ", s, " => ", i, new line))
OD</langsyntaxhighlight>
Output:
<pre>
Line 154 ⟶ 338:
===Other libraries or implementation specific extensions===
As of February 2009 no open source libraries to do this task have been located.
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">begin
% returns with numberInBase set to the number n converted to a string in %
% the specified base. Number must be non-negative and base must be in %
% range 2 to 36 %
procedure convertToBase( integer value n
; integer value base
; string(32) result numberInBase
) ;
begin
string(36) baseDigits;
integer val, strPos;
 
assert( n >= 0 and base >= 2 and base <= 36 );
 
baseDigits := "0123456789abcdefghijklmnopqrstuvwxyz";
numberInBase := " ";
val := n;
strPos := 31;
while
begin
% a(b//c) is the substring of a starting at b with length c. %
% The first character is at position 0. The length must be %
% an integer literal so it is known at compile time. %
numberInBase( strPos // 1 ) := baseDigits( val rem base // 1 );
val := val div base;
strPos := strPos - 1;
val > 0
end
do begin end
end convertToBase ;
 
% returns the string numberInBase converted to an integer assuming %
% numberInBase ia a string in the specified base %
% base must be in range 2 to 36, invalid digits will cause the program %
% to crash, spaces are ignored %
integer procedure convertFromBase( string(32) value numberInBase
; integer value base
) ;
begin
string(36) baseDigits;
integer val, cPos;
 
assert( base >= 2 and base <= 36 );
 
baseDigits := "0123456789abcdefghijklmnopqrstuvwxyz";
val := 0;
for strPos := 0 until 31 do begin
string(1) c;
c := numberInBase( strPos // 1 );
if c not = " " then begin
cPos := 0;
while baseDigits( cPos // 1 ) not = c do cPos := cPos + 1;
val := ( val * base ) + cPos;
end
end;
val
end convertFromBase ;
 
% test the procedures %
string(32) baseNumber;
i_w := 3; % set integer output width %
for i := 2 until 36 do begin
convertToBase( 35, i, baseNumber );
write( 35, i, baseNumber, " ", convertFromBase( baseNumber, i ) );
end
end.</syntaxhighlight>
 
=={{header|AppleScript}}==
{{Trans|JavaScript}}
For more flexibility with digit variants (upper and lower case hex, digits in other languages/scripts etc) we can define '''toBase'''(intBase, n) in terms of a more general '''inBaseDigits'''(strDigits, n) which derives the base from the number of digits to be used:
<syntaxhighlight lang="applescript">-- toBase :: Int -> Int -> String
on toBase(intBase, n)
if (intBase < 36) and (intBase > 0) then
inBaseDigits(items 1 thru intBase of "0123456789abcdefghijklmnopqrstuvwxyz", n)
else
"not defined for base " & (n as string)
end if
end toBase
 
-- inBaseDigits :: String -> Int -> [String]
on inBaseDigits(strDigits, n)
set intBase to length of strDigits
script nextDigit
on |λ|(residue)
set {divided, remainder} to quotRem(residue, intBase)
if divided > 0 then
{just:(item (remainder + 1) of strDigits), new:divided, nothing:false}
else
{nothing:true}
end if
end |λ|
end script
reverse of unfoldr(nextDigit, n) as string
end inBaseDigits
 
-- OTHER FUNCTIONS DERIVABLE FROM inBaseDigits -------------------------------
 
-- inUpperHex :: Int -> String
on inUpperHex(n)
inBaseDigits("0123456789ABCDEF", n)
end inUpperHex
 
-- inDevanagariDecimal :: Int -> String
on inDevanagariDecimal(n)
inBaseDigits("०१२३४५६७८९", n)
end inDevanagariDecimal
 
-- TEST ----------------------------------------------------------------------
on run
script
on |λ|(x)
{{binary:toBase(2, x), octal:toBase(8, x), hex:toBase(16, x)}, ¬
{upperHex:inUpperHex(x), dgDecimal:inDevanagariDecimal(x)}}
end |λ|
end script
map(result, [255, 240])
end run
 
 
-- GENERIC FUNCTIONS ---------------------------------------------------------
 
-- unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
on unfoldr(f, v)
set lst to {}
set recM to {nothing:false, new:v}
tell mReturn(f)
repeat while (not (nothing of recM))
set recM to |λ|(new of recM)
if not nothing of recM then set end of lst to just of recM
end repeat
end tell
lst
end unfoldr
 
-- quotRem :: Integral a => a -> a -> (a, a)
on quotRem(m, n)
{m div n, m mod n}
end quotRem
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn</syntaxhighlight>
{{Out}}
<syntaxhighlight lang="applescript">{{{binary:"11111111", octal:"377", hex:"ff"}, {upperHex:"FF", dgDecimal:"२५५"}},
{{binary:"11110000", octal:"360", hex:"f0"}, {upperHex:"F0", dgDecimal:"२४०"}}}</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">fromBase: function [x,base][
if base=2 [ return from.binary x ]
if base=8 [ return from.octal x ]
if base=16 [ return from.hex x ]
 
return to :integer x
]
 
toBase: function [x,base][
if base=2 [ return as.binary x ]
if base=8 [ return as.octal x ]
if base=16 [ return as.hex x ]
 
return to :string x
]
 
loop 1..20 'i ->
print [
i "base2:" toBase i 2 "base8:" toBase i 8 "base16:" toBase i 16
]
 
print ""
 
print ["101 => from base2:" fromBase "101" 2 "from base8:" fromBase "101" 8 "from base16:" fromBase "101" 16]
print ["123 => from base8:" fromBase "123" 8 "from base16:" fromBase "123" 16]
print ["456 => from base8:" fromBase "456" 8 "from base16:" fromBase "456" 16]</syntaxhighlight>
 
{{out}}
 
<pre>1 base2: 1 base8: 1 base16: 1
2 base2: 10 base8: 2 base16: 2
3 base2: 11 base8: 3 base16: 3
4 base2: 100 base8: 4 base16: 4
5 base2: 101 base8: 5 base16: 5
6 base2: 110 base8: 6 base16: 6
7 base2: 111 base8: 7 base16: 7
8 base2: 1000 base8: 10 base16: 8
9 base2: 1001 base8: 11 base16: 9
10 base2: 1010 base8: 12 base16: a
11 base2: 1011 base8: 13 base16: b
12 base2: 1100 base8: 14 base16: c
13 base2: 1101 base8: 15 base16: d
14 base2: 1110 base8: 16 base16: e
15 base2: 1111 base8: 17 base16: f
16 base2: 10000 base8: 20 base16: 10
17 base2: 10001 base8: 21 base16: 11
18 base2: 10010 base8: 22 base16: 12
19 base2: 10011 base8: 23 base16: 13
20 base2: 10100 base8: 24 base16: 14
 
101 => from base2: 5 from base8: 65 from base16: 257
123 => from base8: 83 from base16: 291
456 => from base8: 302 from base16: 1110</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % number2base(200, 16) ; 12
MsgBox % parse(200, 16) ; 512
 
Line 180 ⟶ 591:
}
Return result
}</langsyntaxhighlight>
alternate implementation contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276241.html#276241 forum]
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % ToBase(29,3)
MsgBox % ToBase(255,16)
 
Line 194 ⟶ 605:
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)
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">function strtol(str, base)
{
symbols = "0123456789abcdefghijklmnopqrstuvwxyz"
Line 224 ⟶ 635:
print strtol("7b", 16)
print ltostr(123, 16)
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbcbasic"> 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%</syntaxhighlight>
'''Output:'''
<pre>
0 (decimal) -> 0 (base 16)
26 (decimal) -> 1a (base 16)
383 (decimal) -> 17f (base 16)
26 (decimal) -> 11010 (base 2)
383 (decimal) -> 101111111 (base 2)
1a (base 16) -> 26 (decimal)
1A (base 16) -> 26 (decimal)
17f (base 16) -> 383 (decimal)
101111111 (base 2) -> 383 (decimal)
</pre>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr";
 
// Reverse a string
let reverse(str) = valof
$( let i = 1
let j = str%0
while i<j
$( let c = str%i
str%i := str%j
str%j := c
i := i+1
j := j-1
$)
resultis str
$)
 
// Convert number to string given base
let itoa(n, base, buf) = valof
$( let digitchar(n) =
n < 10 -> n + '0',
(n - 10) + 'A'
buf%0 := 0
$( buf%0 := buf%0 + 1
buf%(buf%0) := digitchar(n rem base)
n := n / base
$) repeatuntil n<=0
resultis reverse(buf)
$)
 
// Convert string to number given base
let atoi(str, base) = valof
$( let digitval(d, base) =
'0' <= d <= '9' -> d - '0',
'A' <= d <= 'Z' -> (d - 'A') + 10,
'a' <= d <= 'z' -> (d - 'a') + 10,
0
let result = 0
for i=1 to str%0 do
result := result * base + digitval(str%i, base)
resultis result
$)
 
// Examples
let start() be
$( let buffer = vec 64
 
writes("1234 in bases 2-36:*N")
for base=2 to 36 do
writef("Base %I2: %S*N", base, itoa(1234, base, buffer))
writes("*N*"25*" in bases 10-36:*N")
for base=10 to 36 do
writef("Base %I2: %N*N", base, atoi("25", base))
$)</syntaxhighlight>
{{out}}
<pre style='height:50ex;'>1234 in bases 2-36:
Base 2: 10011010010
Base 3: 1200201
Base 4: 103102
Base 5: 14414
Base 6: 5414
Base 7: 3412
Base 8: 2322
Base 9: 1621
Base 10: 1234
Base 11: A22
Base 12: 86A
Base 13: 73C
Base 14: 642
Base 15: 574
Base 16: 4D2
Base 17: 44A
Base 18: 3EA
Base 19: 37I
Base 20: 31E
Base 21: 2GG
Base 22: 2C2
Base 23: 27F
Base 24: 23A
Base 25: 1O9
Base 26: 1LC
Base 27: 1IJ
Base 28: 1G2
Base 29: 1DG
Base 30: 1B4
Base 31: 18P
Base 32: 16I
Base 33: 14D
Base 34: 12A
Base 35: 109
Base 36: YA
 
"25" in bases 10-36:
Base 10: 25
Base 11: 27
Base 12: 29
Base 13: 31
Base 14: 33
Base 15: 35
Base 16: 37
Base 17: 39
Base 18: 41
Base 19: 43
Base 20: 45
Base 21: 47
Base 22: 49
Base 23: 51
Base 24: 53
Base 25: 55
Base 26: 57
Base 27: 59
Base 28: 61
Base 29: 63
Base 30: 65
Base 31: 67
Base 32: 69
Base 33: 71
Base 34: 73
Base 35: 75
Base 36: 77</pre>
 
=={{header|Bracmat}}==
<syntaxhighlight lang="bracmat"> ( 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)))
);</syntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <string.h>
#include <assertstdio.h>
#include <stdint.h>
 
char *to_base(int64_t num, int base)
#define MAX_OUTSTR_LEN 65
char *to_base(long num, int base)
{
static const char *maptbl = "0123456789abcdefghijklmnopqrstuvwxyz";
char *resultbuf[66] = NULL{'\0'};
intchar i=0, j*out;
charuint64_t tn;
int i, len = 0, neg = 0;
if (base > 36) {
fprintf(stderr, "base %d too large\n", base);
return 0;
}
 
/* safe against most negative integer */
if ( base > strlen(map) ) return NULL;
n = ((neg = num < 0)) ? (~num) + 1 : num;
 
do { buf[len++] = tbl[n % base]; } while(n /= base);
result = malloc(sizeof(char)*MAX_OUTSTR_LEN);
 
*result = 0;
out = malloc(len + neg + 1);
do {
for (i = neg; len > 0; result[i++) out[i] = mapbuf[ num%base --len];
if (neg) numout[0] /= base'-';
 
} while(num != 0);
result[i]return = 0out;
for(j=0; j < i/2; j++) { /* invert the rests */
t = result[j];
result[j] = result[i-j-1];
result[i-j-1] = t;
}
return result;
}
 
Line 259 ⟶ 859:
{
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);
assert(*endptr == '\0'); /* if there are any characters left, then string contained invalid characters */
return result;
}
/* 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 main()
}</lang>
{
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;
}</syntaxhighlight>output
<pre>-9223372036854775808 in base 2: -1000000000000000000000000000000000000000000000000000000000000000
383 in base 16: 17f</pre>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">
public static class BaseConverter {
 
/// <summary>
/// Converts a string to a number
/// </summary>
/// <returns>The number.</returns>
/// <param name="s">The string to convert.</param>
/// <param name="b">The base number (between 2 and 36).</param>
public static long stringToLong(string s, int b) {
 
if ( b < 2 || b > 36 )
throw new ArgumentException("Base must be between 2 and 36", "b");
 
checked {
 
int slen = s.Length;
long result = 0;
bool isNegative = false;
 
for ( int i = 0; i < slen; i++ ) {
 
char c = s[i];
int num;
 
if ( c == '-' ) {
// Negative sign
if ( i != 0 )
throw new ArgumentException("A negative sign is allowed only as the first character of the string.", "s");
 
isNegative = true;
continue;
}
 
if ( c > 0x2F && c < 0x3A )
// Numeric character (subtract from 0x30 ('0') to get numerical value)
num = c - 0x30;
else if ( c > 0x40 && c < 0x5B )
// Uppercase letter
// Subtract from 0x41 ('A'), then add 10
num = c - 0x37; // 0x37 = 0x41 - 10
else if ( c > 0x60 && c < 0x7B )
// Lowercase letter
// Subtract from 0x61 ('a'), then add 10
num = c - 0x57; // 0x57 = 0x61 - 10
else
throw new ArgumentException("The string contains an invalid character '" + c + "'", "s");
 
// Check that the digit is allowed by the base.
 
if ( num >= b )
throw new ArgumentException("The string contains a character '" + c + "' which is not allowed in base " + b, "s");
 
// Multiply the result by the base, then add the next digit
 
result *= b;
result += num;
 
}
 
if ( isNegative )
result = -result;
 
return result;
 
}
 
}
 
/// <summary>
/// Converts a number to a string.
/// </summary>
/// <returns>The string.</returns>
/// <param name="n">The number to convert.</param>
/// <param name="b">The base number (between 2 and 36).</param>
public static string longToString(long n, int b) {
// This uses StringBuilder, so it only works with .NET 4.0 or higher. For earlier versions, the StringBuilder
// can be replaced with simple string concatenation.
if ( b < 2 || b > 36 )
throw new ArgumentException("Base must be between 2 and 36", "b");
 
// If the base is 10, call ToString() directly, which returns a base-10 string.
 
if ( b == 10 )
return n.ToString();
 
checked {
long longBase = b;
StringBuilder sb = new StringBuilder();
if ( n < 0 ) {
// Negative numbers
n = -n;
sb.Append('-');
}
long div = 1;
while ( n / div >= b )
// Continue multiplying the dividend by the base until it reaches the greatest power of
// the base which is less than or equal to the number.
div *= b;
while ( true ) {
byte digit = (byte) (n / div);
if ( digit < 10 )
// Numeric character (0x30 = '0')
sb.Append((char) (digit + 0x30));
else
// Alphabetic character (for digits > 10) (0x61 = 'a')
sb.Append((char) (digit + 0x57)); // 0x61 - 10
if ( div == 1 )
// Stop when the dividend reaches 1
break;
n %= div;
div /= b;
}
return sb.ToString();
}
 
}
 
}
</syntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <string>
#include <cstdlib>
#include <algorithm>
Line 295 ⟶ 1,039:
result = result * base + digits.find(num_str[pos]);
return result;
}</langsyntaxhighlight>
 
=={{header|Caché ObjectScript}}==
 
<syntaxhighlight lang="cos">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)
}
 
}</syntaxhighlight>
{{out|Examples}}
<pre>
USER>Write ##class(Utils.Number).ConvertBase(1010101111001101, 2, 16)
ABCD
 
USER>Write $ZHex(26)
1A
USER>Write $ZHex("1A")
26
 
USER>Write ##class(Utils.Number).ConvertBase(26, 10, 16)
1A
USER>Write ##class(Utils.Number).ConvertBase("1A", 16, 10)
26
 
USER>Write ##class(Utils.Number).ConvertBase(6234900123456700, 10, 42, "!$%-0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_")
A9XUCDBHK6
USER>Write ##class(Utils.Number).ConvertBase("A9XUCDBHK6", 42, 10, "!$%-0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_")
6234900123456700</pre>
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">(parse-integer "1a" :radix 16) ; returns multiple values: 26, 2
<lang lisp>(let ((*print-base* 16)
(write-to-string 26 :base 16) ; also "1A"</syntaxhighlight>
*read-base* 16))
 
(write-to-string 26) ; returns the string "1A"
Alternative implementation using FORMAT's ~R directive and #nR reader macro
(read-from-string "1a") ; returns the integer 26
<syntaxhighlight lang="lisp">(defun decimal-to-base-n (number &key (base 16))
(format nil (format nil "~~~dr" base) number))
 
(defun base-n-to-decimal (number &key (base 16))
(read-from-string (format nil "#~dr~d" base number)))</syntaxhighlight>
 
Yet another approach uses FORMAT's ~R in conjunction with ~V for passing arguments to directives (this assumes input as string)
(write-to-string 26 :base 16) ; also "1A"</lang>
<syntaxhighlight lang="lisp">(defun change-base (number input-base output-base)
(format nil "~vr" output-base (parse-integer number :radix input-base)))</syntaxhighlight>
 
=={{header|D}}==
===Using Standard Functions===
D standard library string module included functions to convert number to string at a radix.
<langsyntaxhighlight lang="d">moduleimport std.stdio, std.conv, std.string, std.ascii;
char[] toString(long value, uint radix);
char[] toString(ulong value, uint radix);</lang>
Implementation.
<lang d>module radixstring ;
import std.stdio ;
import std.ctype ;
 
void main() {
const string Digits = "0123456789abcdefghijklmnopqrstuvwxyz" ;
"1abcd".to!int(16).writeln;
 
writeln(60_272_032_366.to!string(36, LetterCase.lower), ' ',
int dtoi(char dc, int radix) {
591_458.to!string(36, LetterCase.lower));
static int[char] digit ;
}</syntaxhighlight>
char d = tolower(dc) ;
{{out}}
if (digit.length == 0) // not init yet
<pre>109517
foreach(i,c ; Digits)
rosetta code</pre>
digit[c] = i ;
 
if (radix > 1 & radix <= digit.length)
===One Implementation===
if (d in digit)
<syntaxhighlight lang="d">import std.stdio, std.array, std.ascii;
if (digit[d] < radix)
 
return digit[d] ;
immutable string mDigits = digits ~ lowercase;
return int.min ; // a negative for error ;
 
ulong atoiRadix(in string str, in uint radix=10, int* consumed=null)
nothrow {
static int dtoi(in char dc, in uint radix) nothrow {
static int[immutable char] digit;
immutable char d = dc.toLower;
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;
}
 
ulongstring AtoIitoaRadix(stringulong strnum, intin uint radix = 10,) int* consumed = null)pure {nothrow
in {
ulong result = 0;
assert(radix > 1 && radix <= mDigits.length);
int sp = 0 ;
} body {
for(; sp < str.length ; sp++) {
string result;
int d = dtoi(str[sp], radix) ;
ifwhile (dnum >= 0) // valid digit char{
result = radix*resultimmutable +uint d ; = num % radix;
result = mDigits[d] ~ result;
else
break num = (num - d) / radix;
} }
return result.empty ? "0" : result;
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 ;
}
 
void main() {
string ItoA(ulong num, int radix = 10) {
immutable string numStr = "1ABcdxyz???";
string result = null ;
 
// if (radix < 2 || radix > Digits.length) throw Error
while (num >int 0) {ate;
intwritef("'%s' (base %d) = num %d", radixnumStr, ;16,
atoiRadix(numStr, 16, &ate));
result = Digits[d]~ result ;
 
num = (num - d) / radix ;
if (ate <= 0)
}
writefln("\tConverted only: '%s'", numStr[0 .. -ate]);
return result == null ? "0" : result ;
else
writeln();
 
writeln(itoaRadix(60_272_032_366, 36), " ",
itoaRadix(591_458, 36));
}</syntaxhighlight>
{{out}}
<pre>'1ABcdxyz???' (base 16) = 109517 Converted only: '1ABcd'
rosetta code</pre>
 
===Alternative Implementation===
{{trans|Haskell}}
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.ascii, std.array, std.string;
 
alias Digits = ubyte[];
 
Digits toBase(ulong number, in ubyte base) pure nothrow @safe {
Digits result;
while (number) {
result = number % base ~ result;
number /= base;
}
return result;
}
 
enum fromBase = (in Digits digits, in ubyte base) pure nothrow @safe @nogc =>
void main(string[] args) {
reduce!((n, k) => n * base + k)(0UL, digits);
string numstr = "1ABcdxyz???" ;
 
int ate ;
immutable myDigits = digits ~ lowercase;
writef("%s (%d) = %d",numstr, 16, AtoI(numstr, 16, &ate)) ;
 
if(ate <= 0) writefln("\tcheck: %s<%s>",numstr[0..-ate], numstr[-ate..$]) ;
enum fromDigits = (in Digits digits) pure nothrow /*@safe*/ =>
else writefln() ;
digits.map!(d => myDigits[d]).array;
writefln(ItoA(60272032366,36)," ",ItoA(591458,36)) ;
 
}</lang>
enum convert = (in dchar d) pure nothrow @safe @nogc =>
cast(ubyte)(d.isDigit ? d - '0' : std.ascii.toLower(d) - 'a' + 10);
 
enum toDigits = (in string number) pure nothrow @safe =>
number.representation.map!convert.array;
 
void main() {
"1ABcd".toDigits.fromBase(16).writeln;
}</syntaxhighlight>
{{out}}
109517
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
function GetRadixString(L: Integer; Radix: Byte): string;
{Converts integer a string of any radix}
const RadixChars: array[0..35] Of char =
('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');
var I: integer;
var S: string;
var Sign: string[1];
begin
Result:='';
If (L < 0) then
begin
Sign:='-';
L:=Abs(L);
end
else Sign:='';
S:='';
repeat
begin
I:=L mod Radix;
S:=RadixChars[I] + S;
L:=L div Radix;
end
until L = 0;
Result:=Sign + S;
end;
 
procedure ShowRadixConvertion(Memo: TMemo);
var B,N: integer;
var S,RS: string;
begin
N:=6502;
for B:=2 to 23 do
begin
RS:=GetRadixString(N,B);
RS:=LowerCase(RS);
Memo.Lines.Add(Format('%5d -> base: %3D = %15S',[N,B,RS]));
end;
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
6502 -> base: 2 = 1100101100110
6502 -> base: 3 = 22220211
6502 -> base: 4 = 1211212
6502 -> base: 5 = 202002
6502 -> base: 6 = 50034
6502 -> base: 7 = 24646
6502 -> base: 8 = 14546
6502 -> base: 9 = 8824
6502 -> base: 10 = 6502
6502 -> base: 11 = 4981
6502 -> base: 12 = 391a
6502 -> base: 13 = 2c62
6502 -> base: 14 = 2526
6502 -> base: 15 = 1dd7
6502 -> base: 16 = 1966
6502 -> base: 17 = 1588
6502 -> base: 18 = 1214
6502 -> base: 19 = i04
6502 -> base: 20 = g52
6502 -> base: 21 = efd
6502 -> base: 22 = d9c
6502 -> base: 23 = c6g
</pre>
 
 
=={{header|E}}==
<langsyntaxhighlight lang="e">def stringToInteger := __makeInt
def integerToString(i :int, base :int) {
return i.toString(base)
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">? stringToInteger("200", 16)
# value: 512
 
? integerToString(200, 16)
# value: "c8"</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func$ num2str n base .
if n = 0
return "0"
.
d = n mod base
if d > 9
d += 39
.
d$ = strchar (d + 48)
if n < base
return d$
.
return num2str (n div base) base & d$
.
func str2num s$ base .
r = 0
for c$ in strchars s$
d = strcode c$ - 48
if d > 9
d -= 39
.
r = r * base + d
.
return r
.
print num2str 253 16
print str2num "fd" 16
print num2str 0 16
</syntaxhighlight>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">iex(1)> String.to_integer("ffff", 16)
65535
iex(2)> Integer.to_string(255, 2)
"11111111"
iex(3)> String.to_integer("NonDecimalRadices", 36)
188498506820338115928429652</syntaxhighlight>
 
=={{header|Erlang}}==
 
{{out}}
<pre>
12> erlang:list_to_integer("ffff", 17).
78300
13> erlang:integer_to_list(63, 3).
"2100"
</pre>
 
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">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</syntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USE: math.parser
 
12345 16 >base .
"3039" 16 base> .</langsyntaxhighlight>
 
=={{header|Forth}}==
Forth has a global user variable, BASE, which determines the radix used for parsing, interpretation, and printing of integers. This can handle bases from 2-36, but there are two words to switch to the most popular bases, DECIMAL and HEX.
<langsyntaxhighlight lang="forth">42 dup
2 base !
. \ 101010
hex
. \ 2A
decimal</langsyntaxhighlight>
 
Many variants of Forth support literals in some bases, such as hex, using a prefix
<syntaxhighlight lang ="forth">$ff . \ 255</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{Works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">MODULE Conversion
IMPLICIT NONE
CHARACTER(36) :: alphanum = "0123456789abcdefghijklmnopqrstuvwxyz"
Line 443 ⟶ 1,503:
WRITE (*,*) ToBase(16, 26)
 
END PROGRAM</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function min(x As Integer, y As Integer) As Integer
Return IIf(x < y, x, y)
End Function
 
Function convertToBase (n As UInteger, b As UInteger) As String
If n < 2 OrElse b < 2 OrElse b = 10 OrElse b > 36 Then Return Str(n)
Dim result As String = ""
Dim digit As Integer
While n > 0
digit = n Mod b
If digit < 10 Then
result = digit & result
Else
result = Chr(digit + 87) + result
End If
n \= b
Wend
Return result
End Function
 
Function convertToDecimal (s As Const String, b As UInteger) As UInteger
If b < 2 OrElse b > 36 Then Return 0
Dim t As String = LCase(s)
Dim result As UInteger = 0
Dim digit As Integer
Dim multiplier As Integer = 1
For i As Integer = Len(t) - 1 To 0 Step - 1
digit = -1
If t[i] >= 48 AndAlso t[i] <= min(57, 47 + b) Then
digit = t[i] - 48
ElseIf b > 10 AndAlso t[i] >= 97 AndAlso t[i] <= min(122, 87 + b) Then
digit = t[i] - 87
End If
If digit = -1 Then Return 0 '' invalid digit present
If digit > 0 Then result += multiplier * digit
multiplier *= b
Next
Return result
End Function
 
Dim s As String
 
For b As UInteger = 2 To 36
Print "36 base ";
Print Using "##"; b;
s = ConvertToBase(36, b)
Print " = "; s; Tab(21); " -> base ";
Print Using "##"; b;
Print " = "; convertToDecimal(s, b)
Next
 
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
36 base 2 = 100100 -> base 2 = 36
36 base 3 = 1100 -> base 3 = 36
36 base 4 = 210 -> base 4 = 36
36 base 5 = 121 -> base 5 = 36
36 base 6 = 100 -> base 6 = 36
36 base 7 = 51 -> base 7 = 36
36 base 8 = 44 -> base 8 = 36
36 base 9 = 40 -> base 9 = 36
36 base 10 = 36 -> base 10 = 36
36 base 11 = 33 -> base 11 = 36
36 base 12 = 30 -> base 12 = 36
36 base 13 = 2a -> base 13 = 36
36 base 14 = 28 -> base 14 = 36
36 base 15 = 26 -> base 15 = 36
36 base 16 = 24 -> base 16 = 36
36 base 17 = 22 -> base 17 = 36
36 base 18 = 20 -> base 18 = 36
36 base 19 = 1h -> base 19 = 36
36 base 20 = 1g -> base 20 = 36
36 base 21 = 1f -> base 21 = 36
36 base 22 = 1e -> base 22 = 36
36 base 23 = 1d -> base 23 = 36
36 base 24 = 1c -> base 24 = 36
36 base 25 = 1b -> base 25 = 36
36 base 26 = 1a -> base 26 = 36
36 base 27 = 19 -> base 27 = 36
36 base 28 = 18 -> base 28 = 36
36 base 29 = 17 -> base 29 = 36
36 base 30 = 16 -> base 30 = 36
36 base 31 = 15 -> base 31 = 36
36 base 32 = 14 -> base 32 = 36
36 base 33 = 13 -> base 33 = 36
36 base 34 = 12 -> base 34 = 36
36 base 35 = 11 -> base 35 = 36
36 base 36 = 10 -> base 36 = 36
</pre>
 
=={{header|FunL}}==
Converting from integer to string:
<syntaxhighlight lang="funl">$stdout = int( '1a', 16 )</syntaxhighlight>
 
{{out}}
 
<pre>
26
</pre>
 
Converting from string to integer:
<syntaxhighlight lang="funl">$stdout = str( 26, 16 )</syntaxhighlight>
 
{{out}}
 
<pre>
1a
</pre>
 
=={{header|Go}}==
The standard <code>strconv</code> package functions <code>ParseInt</code>, <code>ParseUint</code>, <code>FormatInt</code>, <code>FormatUint</code>,
<lang go>import "strconv"
and the standard <code>math/big</code> package method <code>SetString</code>,
all accept a base argument <code>2 ≤ base ≤ 36</code>.
 
Note, there is no equivalent formatting function provided for a <code>big.Int</code>, only the standard bases are available via <code>fmt</code> integer formatting verbs
s := strconv.Itob(26, 16) // returns the string 1a
(binary <code>%b</code>, octal <code>%o</code>, decimal <code>%d</code>, and hexidecimal <code>%x</code> or <code>%X</code>).
i,_ := strconv.Btoi64("1a", 16) // returns the integer 26</lang>
<syntaxhighlight lang="go">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)
}
}</syntaxhighlight>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def radixParse = { s, radix -> Integer.parseInt(s, radix) }
def radixFormat = { i, radix -> Integer.toString(i, radix) }</langsyntaxhighlight>
 
Test Program:
<langsyntaxhighlight lang="groovy">def numString = '101'
(2..Character.MAX_RADIX).each { radix ->
def value = radixParse(numString, radix)
Line 467 ⟶ 1,666:
assert valM2str == biggestDigit + biggestDigit
printf ("%3s (%2d) - 2 (10) == %4s (%2d)\n", numString, radix, valM2str, radix)
}</langsyntaxhighlight>
 
Output:
Line 542 ⟶ 1,741:
 
=={{header|Haskell}}==
 
Using built-in functions to convert integer into string, and vice versa, at any base up to 16:
 
<syntaxhighlight lang="haskell">Prelude> Numeric.showIntAtBase 16 Char.intToDigit 42 ""
"2a"
Prelude> fst $ head $ Numeric.readInt 16 Char.isHexDigit Char.digitToInt "2a"
42</syntaxhighlight>
 
It's actually more useful to represent digits internally as numbers instead of characters, because then one can define operations that work directly on this representation.
Line 547 ⟶ 1,753:
So conversion to and from digits represented as 0-9 and a-z is done in an additional step.
 
<langsyntaxhighlight lang="haskell">import Data.List
import Data.Char
 
Line 567 ⟶ 1,773:
convert c | isDigit c = ord c - ord '0'
| isUpper c = ord c - ord 'A' + 10
| isLower c = ord c - ord 'a' + 10</langsyntaxhighlight>
 
Example:
 
<langsyntaxhighlight lang="haskell">*Main> toAlphaDigits $ toBase 16 $ 42
"2a"
*Main> fromBase 16 $ fromAlphaDigits $ "2a"
42</langsyntaxhighlight>
 
 
Or, to allow for digit variants like upper case vs lower case Hexadecimal, we can express our conversion function(s) in terms of a more general '''inBaseDigits''' function which, given an ordered list of digits as its first argument, returns an Int -> String unfold function. (The base is the length of the digit list).
 
If we want to assume a default character set, then a general '''toBase''' (Int -> Int -> String) can be also be derived from '''inBaseDigits'''.
 
<syntaxhighlight lang="haskell">import Data.Bifunctor (first)
import Data.List (unfoldr)
import Data.Tuple (swap)
import Data.Bool (bool)
 
 
inBaseDigits :: String -> Int -> String
inBaseDigits ds n =
let base = length ds
in reverse $
unfoldr
((<*>)
(bool Nothing . Just . first (ds !!) . swap . flip quotRem base)
(0 <))
n
 
inLowerHex :: Int -> String
inLowerHex = inBaseDigits "0123456789abcdef"
inUpperHex :: Int -> String
inUpperHex = inBaseDigits "0123456789ABCDEF"
inBinary :: Int -> String
inBinary = inBaseDigits "01"
inOctal :: Int -> String
inOctal = inBaseDigits "01234567"
inDevanagariDecimal :: Int -> String
inDevanagariDecimal = inBaseDigits "०१२३४५६७८९"
inHinduArabicDecimal :: Int -> String
inHinduArabicDecimal = inBaseDigits "٠١٢٣٤٥٦٧٨٩"
toBase :: Int -> Int -> String
toBase intBase n
| (intBase < 36) && (intBase > 0) =
inBaseDigits (take intBase (['0' .. '9'] ++ ['a' .. 'z'])) n
| otherwise = []
main :: IO ()
main =
mapM_ putStrLn $
[ inLowerHex
, inUpperHex
, inBinary
, inOctal
, toBase 16
, toBase 2
, inDevanagariDecimal
, inHinduArabicDecimal
] <*>
[254]</syntaxhighlight>
 
{{Out}}
<pre>fe
FE
11111110
376
fe
11111110
२५४
٢٥٤</pre>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">CHARACTER txt*80
 
num = 36^7 -1 ! 7836416410
Line 604 ⟶ 1,880:
temp = INT(temp / base)
ENDDO
END</langsyntaxhighlight>
<langsyntaxhighlight lang="hicest">num=7836416410; txt=zzzzzzz; 7836416410;</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon natively take integers in radix form for bases 2 through 36. There is no need to convert to integer as the value will be coerced when needed. However, a conversion routine is needed to convert integers back into radix form.
 
<syntaxhighlight lang="icon">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</syntaxhighlight>
 
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/src/procs/printf.icn printf.icn provides printf]
There are several conversion routines for bases in the IPL, however, none returns the input radix form.
 
Output:<pre>ns=16r5a -> n=90 -> 8r132
ns=16r5a -> n=90 -> 12r76
ns=16r5a -> n=90 -> 16r5a
ns=-12r1a -> n=-22 -> -8r26
ns=-12r1a -> n=-22 -> -12r1a
ns=-12r1a -> n=-22 -> -16r16</pre>
 
=={{header|J}}==
J supports direct specification of numbersnative precision integers by base. The numbers are expressed as the base to be used (using base 10), the letter b, followed by the number itself. Following the initial letter b, other (lower case) letters represent "digts" 10 (a) through 35 (z), as in these examples:
<langsyntaxhighlight lang="j"> 2b100 8b100 10b10010b_100 16b100 36b100 36bzy
4 64 100_100 256 1296 1294</langsyntaxhighlight>
 
Programs for conversion of numeric values to literals, and of literals to numbers:
Additionally, J has primitives [http://www.jsoftware.com/help/dictionary/d401.htm #.] and [http://www.jsoftware.com/help/dictionary/d402.htm #:] for dealing with base conversion issues.
<lang j>numerals=: '0123456789abcdefghijklmnopqrstuvwxyz'
 
Here are programs for conversion of numeric values to literals, and of literals to numbers:
<syntaxhighlight lang="j">numerals=: '0123456789abcdefghijklmnopqrstuvwxyz'
baseNtoL=: numerals {~ #.inv
baseLtoN=: [ #. numerals i. ]</langsyntaxhighlight>
Examples of use:
<langsyntaxhighlight lang="j"> 2 baseNtoL 100 101
1100100
1100101
Line 622 ⟶ 1,942:
1a
36 baseLtoN 'zy'
1294</langsyntaxhighlight>
These may be combined so the conversion performed is derived from the type of argument received.
<langsyntaxhighlight lang="j"> base=: baseNtoL :: baseLtoN
16 base 'aa'
170
16 base 170
aa</langsyntaxhighlight>
See also primary verbs [http://www.jsoftware.com/help/dictionary/d401.htm Base] and [http://www.jsoftware.com/help/dictionary/d402.htm Antibase].
 
=={{header|Java}}==
for long's:
<langsyntaxhighlight lang="java">public static long backToTen(String num, int oldBase){
return Long.parseLong(num, oldBase); //takes both uppercase and lowercase letters
}
Line 640 ⟶ 1,960:
public static String tenToBase(long num, int newBase){
return Long.toString(num, newBase);//add .toUpperCase() for capital letters
}</langsyntaxhighlight>
 
for BigInteger's:
<langsyntaxhighlight lang="java">public static BigInteger backToTenBig(String num, int oldBase){
return new BigInteger(num, oldBase); //takes both uppercase and lowercase letters
}
Line 649 ⟶ 1,969:
public static String tenBigToBase(BigInteger num, int newBase){
return num.toString(newBase);//add .toUpperCase() for capital letters
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
===ES5===
<lang javascript>k = 26
<syntaxhighlight lang="javascript">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.</langsyntaxhighlight>
 
Converts a number of arbitrary length from any base to any base
Limitation: Any base or number that causes accumulator to overflow will lose precision!!
Debugging or following the process is easy as it is kept in the expected base string format and order.
<syntaxhighlight lang="javascript">
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));</syntaxhighlight>
Using BigInteger, can convert any base.
<syntaxhighlight lang="javascript">
// 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('');
}
</syntaxhighlight>
 
===ES6===
 
For more flexibility with digit variants (upper and lower case hex, digits in other languages/scripts etc) we can define '''toBase'''(intBase, n) in terms of a more general '''inBaseDigits'''(strDigits, n) which derives the base from the number of digits to be used.
 
<syntaxhighlight lang="javascript">(() => {
'use strict';
 
// toBase :: Int -> Int -> String
const toBase = (intBase, n) =>
intBase < 36 && intBase > 0 ?
inBaseDigits('0123456789abcdef'.substr(0, intBase), n) : [];
 
 
// inBaseDigits :: String -> Int -> [String]
const inBaseDigits = (digits, n) => {
const intBase = digits.length;
 
return unfoldr(maybeResidue => {
const [divided, remainder] = quotRem(maybeResidue.new, intBase);
 
return {
valid: divided > 0,
value: digits[remainder],
new: divided
};
}, n)
.reverse()
.join('');
};
 
 
// GENERIC FUNCTIONS
 
// unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
const unfoldr = (mf, v) => {
var xs = [];
return (until(
m => !m.valid,
m => {
const m2 = mf(m);
return (
xs = xs.concat(m2.value),
m2
);
}, {
valid: true,
value: v,
new: v,
}
), xs);
};
 
// curry :: ((a, b) -> c) -> a -> b -> c
const curry = f => a => b => f(a, b);
 
// until :: (a -> Bool) -> (a -> a) -> a -> a
const until = (p, f, x) => {
let v = x;
while (!p(v)) v = f(v);
return v;
}
 
// quotRem :: Integral a => a -> a -> (a, a)
const quotRem = (m, n) => [Math.floor(m / n), m % n];
 
// show :: a -> String
const show = x => JSON.stringify(x, null, 2);
 
 
// OTHER FUNCTIONS DERIVABLE FROM inBaseDigits
 
// inLowerHex :: Int -> String
const inLowerHex = curry(inBaseDigits)('0123456789abcdef');
 
/// inUpperHex :: Int -> String
const inUpperHex = curry(inBaseDigits)('0123456789ABCDEF');
 
// inOctal :: Int -> String
const inOctal = curry(inBaseDigits)('01234567');
 
// inDevanagariDecimal :: Int -> String
const inDevanagariDecimal = curry(inBaseDigits)('०१२३४५६७८९');
 
 
// TESTS
// testNumber :: [Int]
const testNumbers = [255, 240];
 
return testNumbers.map(n => show({
binary: toBase(2, n),
base5: toBase(5, n),
hex: toBase(16, n),
upperHex: inUpperHex(n),
octal: inOctal(n),
devanagariDecimal: inDevanagariDecimal(n)
}));
})();</syntaxhighlight>
 
{{Out}}
<pre>{
"binary": "11111111",
"base5": "2010",
"hex": "ff",
"upperHex": "FF",
"octal": "377",
"devanagariDecimal": "२५५"
}, {
"binary": "11110000",
"base5": "1430",
"hex": "f0",
"upperHex": "F0",
"octal": "360",
"devanagariDecimal": "२४०"
}</pre>
 
=={{header|Joy}}==
<syntaxhighlight lang="joy">DEFINE
digit == "0123456789abcdefghijklmnopqrstuvwxyz" of;
itostr ==
"" rollup
[>=] [dup rollup div digit rotated swons rollup] while
pop digit swons.
 
26 16 itostr.
"1a" 16 strtol.
</syntaxhighlight>
{{out}}
<pre>"1a"
26</pre>
 
=={{header|jq}}==
<syntaxhighlight lang="jq"># Convert the input integer to a string in the specified base (2 to 36 inclusive)
def convert(base):
def stream:
recurse(if . >= base then ./base|floor else empty end) | . % base ;
[stream] | reverse
| if base < 10 then map(tostring) | join("")
elif base <= 36 then map(if . < 10 then 48 + . else . + 87 end) | implode
else error("base too large")
end;
 
# input string is converted from "base" to an integer, within limits
# of the underlying arithmetic operations, and without error-checking:
def to_i(base):
explode
| reverse
| map(if . > 96 then . - 87 else . - 48 end) # "a" ~ 97 => 10 ~ 87
| reduce .[] as $c
# state: [power, ans]
([1,0]; (.[0] * base) as $b | [$b, .[1] + (.[0] * $c)])
| .[1];</syntaxhighlight>
'''Example''':
<syntaxhighlight lang="jq">(255 | convert(16)),
("ff" | to_i(16)),
("10" | to_i(10))</syntaxhighlight>
{{Out}}
$jq -M -r -n -f Non-decimal_radices.jq
ff
255
10
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">
@show string(185, base=2)
@show string(185, base=3)
@show string(185, base=4)
@show string(185, base=5)
@show string(185, base=6)
@show string(185, base=7)
@show string(185, base=8)
@show string(185, base=9)
@show string(185, base=10)
@show string(185, base=11)
@show string(185, base=12)
@show string(185, base=13)
@show string(185, base=14)
@show string(185, base=15)
@show string(185, base=16)
</syntaxhighlight>{{out}}
<pre>
string(185, base = 2) = "10111001"
string(185, base = 3) = "20212"
string(185, base = 4) = "2321"
string(185, base = 5) = "1220"
string(185, base = 6) = "505"
string(185, base = 7) = "353"
string(185, base = 8) = "271"
string(185, base = 9) = "225"
string(185, base = 10) = "185"
string(185, base = 11) = "159"
string(185, base = 12) = "135"
string(185, base = 13) = "113"
string(185, base = 14) = "d3"
string(185, base = 15) = "c5"
string(185, base = 16) = "b9"
</pre>
 
=={{header|Kotlin}}==
An approach from first principles rather than using Java library functions:
{{trans|FreeBASIC}}
<syntaxhighlight lang="scala">// version 1.0.6
 
fun min(x: Int, y: Int) = if (x < y) x else y
 
fun convertToBase(n: Int, b: Int): String {
if (n < 2 || b < 2 || b == 10 || b > 36) return n.toString() // leave as decimal
val sb = StringBuilder()
var digit: Int
var nn = n
while (nn > 0) {
digit = nn % b
if (digit < 10) sb.append(digit)
else sb.append((digit + 87).toChar())
nn /= b
}
return sb.reverse().toString()
}
 
fun convertToDecimal(s: String, b: Int): Int {
if (b !in 2..36) throw IllegalArgumentException("Base must be between 2 and 36")
if (b == 10) return s.toInt()
val t = s.toLowerCase()
var result = 0
var digit: Int
var multiplier = 1
for (i in t.length - 1 downTo 0) {
digit = -1
if (t[i] >= '0' && t[i] <= min(57, 47 + b).toChar())
digit = t[i].toInt() - 48
else if (b > 10 && t[i] >= 'a' && t[i] <= min(122, 87 + b).toChar())
digit = t[i].toInt() - 87
if (digit == -1) throw IllegalArgumentException("Invalid digit present")
if (digit > 0) result += multiplier * digit
multiplier *= b
}
return result
}
 
fun main(args: Array<String>) {
for (b in 2..36) {
val s = convertToBase(36, b)
val f = "%2d".format(b)
println("36 base $f = ${s.padEnd(6)} -> base $f = ${convertToDecimal(s, b)}")
}
}</syntaxhighlight>
 
{{out}}
<pre>
36 base 2 = 100100 -> base 2 = 36
36 base 3 = 1100 -> base 3 = 36
36 base 4 = 210 -> base 4 = 36
36 base 5 = 121 -> base 5 = 36
36 base 6 = 100 -> base 6 = 36
36 base 7 = 51 -> base 7 = 36
36 base 8 = 44 -> base 8 = 36
36 base 9 = 40 -> base 9 = 36
36 base 10 = 36 -> base 10 = 36
36 base 11 = 33 -> base 11 = 36
36 base 12 = 30 -> base 12 = 36
36 base 13 = 2a -> base 13 = 36
36 base 14 = 28 -> base 14 = 36
36 base 15 = 26 -> base 15 = 36
36 base 16 = 24 -> base 16 = 36
36 base 17 = 22 -> base 17 = 36
36 base 18 = 20 -> base 18 = 36
36 base 19 = 1h -> base 19 = 36
36 base 20 = 1g -> base 20 = 36
36 base 21 = 1f -> base 21 = 36
36 base 22 = 1e -> base 22 = 36
36 base 23 = 1d -> base 23 = 36
36 base 24 = 1c -> base 24 = 36
36 base 25 = 1b -> base 25 = 36
36 base 26 = 1a -> base 26 = 36
36 base 27 = 19 -> base 27 = 36
36 base 28 = 18 -> base 28 = 36
36 base 29 = 17 -> base 29 = 36
36 base 30 = 16 -> base 30 = 36
36 base 31 = 15 -> base 31 = 36
36 base 32 = 14 -> base 32 = 36
36 base 33 = 13 -> base 33 = 36
36 base 34 = 12 -> base 34 = 36
36 base 35 = 11 -> base 35 = 36
36 base 36 = 10 -> base 36 = 36
</pre>
 
=={{header|LFE}}==
 
Converting decimal numbers 26 and 3000 in LFE, using some different mechanisms:
<syntaxhighlight lang="lisp">
> (: erlang list_to_integer '"1a" 16)
26
> #x1a
26
> (: erlang integer_to_list 26 16)
"1A"
> (: erlang list_to_integer '"101110111000" 2)
3000
> #b101110111000
3000
> (: erlang integer_to_list 3000 2)
"101110111000"
</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb"> ' 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
</syntaxhighlight>
 
=={{header|Lua}}==
Only had to write 'dec2base' as the reverse is provided by the in-built function 'tonumber'
<syntaxhighlight lang="lua">function dec2base (base, n)
local result = ""
repeat
local digit = n % base
if digit > 9 then
digit = string.char(digit + 87)
end
result = digit .. result
n = n // base
until n == 0
return result
end
 
local x = dec2base(16, 26)
print(x) --> 1a
print(tonumber(x, 16)) --> 26</syntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
k$=lambda$ (m, b as integer=16) -> {
if b<2 or b>16 then error "base out of range"
if m=0 then ="0" : exit
z$="0123456789ABCDEF"
=lambda$ z$, b (m) ->{
=if$(m=0->"", lambda$(m div b)+mid$(z$, m mod b + 1, 1))
}(m)
}
k=lambda (m$, b as integer=16) -> {
if b<2 or b>16 then error "base out of range"
m$=trim$(m$)
if m$="0" then =0 : exit
z$="0123456789ABCDEF"
=lambda z$, b (m$) ->{
=if(Len(m$)=0->0, lambda(mid$(m$,2))+(instr(z$, left$(m$,1))-1)*b**(len(m$)-1))
}(m$)
}
Print k$(0)="0", k("0")=0
Print k$(65535)="FFFF", k("FFFF", 16)=65535
Print k$(0xF00F)="F00F", k("F00F", 16)=0xF00F
Print k$(0xFFFFFFFF)="FFFFFFFF", k("FFFFFFFF", 16)=0xFFFFFFFF
Print k$(100, 8)="144", k("144", 8)=100
Print k$(100, 2)="1100100", k("1100100", 2)=100
}
Checkit
</syntaxhighlight>
Output:
<pre>
True True
True True
True True
True True
True True
True True
</pre>
 
 
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">eval(26,16)
define(`frombase',`eval(0r$2:$1)')
frombase(1a,16)</langsyntaxhighlight>
 
Output:
Line 669 ⟶ 2,443:
26
</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">#converts a number to a given based represented by a string
to_base := proc(num, based)
local i;
local chart := "0123456789abcdefghijklmnopqrstuvwxyz";
local conversion := ListTools:-Reverse((convert(num,base,based)));
local str := StringTools:-StringBuffer();
for i in conversion do
str:-append(chart[i+1]);
end do;
return str;
end proc:
 
#find the location of char in chart
find_digit := proc(char)
if (StringTools:-HasAlpha(char)) then
return (StringTools:-Ord(char) - 87);
else
return (StringTools:-Ord(char) - 48);
end if;
end proc:
 
#converts a string with given base to a number
from_base := proc(str, base)
local char;
local result := 0;
for char in str do
result *= base;
result += find_digit(char);
end do;
return result;
end proc:</syntaxhighlight>
{{Out|Usage}}
<pre>
to_base(32, 11);
to_base(0, 16);
from_base("2a", 11);
from_base("1a",16);
</pre>
{{Out|Output}}
<pre>
"2a"
"0"
32
26
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Use the built-in functions IntegerString[] and FromDigits[]:
<syntaxhighlight lang="mathematica">IntegerString[26,16]
FromDigits["1a", 16])</syntaxhighlight>
{{out}}
<pre>"1a"
26</pre>
 
=={{header|MATLAB}} / {{header|Octave}}==
Use the built-in functions base2dec() and dec2base():
<syntaxhighlight lang="matlab">dec2base(26,16)
base2dec('1a', 16)</syntaxhighlight>
 
Output:
<pre>1A
 
26</pre>
 
=={{header|МК-61/52}}==
<pre>
П8 -> 1 0 П0 ПП 13 ИП7 П0 ИП8
ПП 13 С/П П7 -> П6 -> 1 П4 П5
Сx <-> ^ ПП 68 П3 - ИП7 * П2
ПП 68 ИП4 ИП6 * П4 / + ИП2 ИП1
- x#0 45 L0 27 -> ИП3 ^ ИП7 /
ПП 68 ИП7 * - ИП5 * + ИП5 ИП6
* П5 -> ИП1 x=0 47 -> В/О 1 +
П1 КИП1 -> -> ИП1 В/О
</pre>
 
Input: ''N<sub>m</sub> ^ m ^ n В/О С/П''.
 
Output: ''N<sub>n</sub> -> PX''.
 
=={{header|NetRexx}}==
In NetRexx numbers are held as Rexx strings so you can take advantage of Java's BigInteger to do radix conversions.
<syntaxhighlight lang="netrexx">/* 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)
</syntaxhighlight>
'''Output:'''
<pre>
1234[10]: 1234[10] == 1234[10]
01234[08]: 668[10] == 1234[08]
fe[16]: 254[10] == fe[16]
f0e[16]: 3854[10] == f0e[16]
0[10]: 0[10] == 0[10]
00[02]: 0[10] == 0[02]
11[02]: 3[10] == 11[02]
070[08]: 56[10] == 70[08]
77[08]: 63[10] == 77[08]
f0e[16]: 3854[10] == f0e[16]
070[16]: 112[10] == 70[16]
0xf0e[36]: 1559102[10] == xf0e[36]
000999ABCXYZ[36]: 26115481426427[10] == 999abcxyz[36]
ff[36]: 555[10] == ff[36]
f[16]: 15[10] == f[16]
Error -- Input: z, radix: 37
java.lang.NumberFormatException: Radix out of range
at java.math.BigInteger.<init>(BigInteger.java:294)
at RNonDecRadixConvert.toDecimal(RNonDecRadixConvert.nrx:77)
at RNonDecRadixConvert.main(RNonDecRadixConvert.nrx:57)
</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import strutils
 
proc reverse(a: string): string =
result = newString(a.len)
for i, c in a:
result[a.high - i] = c
 
const digits = "0123456789abcdefghijklmnopqrstuvwxyz"
 
proc toBase[T](num: T, base: range[2..36]): string =
if num == 0: return "0"
result = ""
if num < 0: result.add '-'
var tmp = abs(num)
var s = ""
while tmp > 0:
s.add digits[int(tmp mod base)]
tmp = tmp div base
result.add s.reverse
 
proc fromBase(str: string, base: range[2..36]): BiggestInt =
var str = str
let first = if str[0] == '-': 1 else: 0
 
for i in first .. str.high:
let c = str[i].toLowerAscii
assert c in digits[0 ..< base]
result = result * base + digits.find c
 
if first == 1: result *= -1
 
echo 26.toBase 16
echo "1a".fromBase 16</syntaxhighlight>
Output:
<pre>1a
26</pre>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let int_of_basen n str =
match n with
| 16 -> int_of_string("0x" ^ str)
Line 682 ⟶ 2,641:
| 16 -> Printf.sprintf "%x" d
| 8 -> Printf.sprintf "%o" d
| _ -> failwith "unhandled"</langsyntaxhighlight>
 
# basen_of_int 16 26 ;;
Line 690 ⟶ 2,649:
- : int = 26
 
A real base conversion exampleimplementation: {{trans|Haskell}}
<syntaxhighlight lang="ocaml">let basen_of_int b n : string =
let tab = "0123456789abcdefghijklmnopqrstuvwxyz" in
let rec aux x l =
if x < b
then tab.[x] :: l
else aux (x / b) (tab.[x mod b] :: l)
in
String.of_seq (List.to_seq (aux n []))
 
<lang ocaml>let to_basebasen_to_int b vds : int =
let recof_sym to_base' a vc =
ifint_of_char vc =- 0match thenc with
| '0' .. '9' -> int_of_char '0'
a
| 'a' .. 'z' -> int_of_char 'a' - 10
else
| to_base'A' (v.. mod'Z' b-> ::int_of_char a) (v'A' /- b)10
| _ -> invalid_arg "unkown digit"
in
String.fold_left (fun n d -> n * b + of_sym d) 0 ds</syntaxhighlight>
to_base' [] v
 
Example:
let from_base b ds =
<pre>
List.fold_left (fun n k -> n * b + k) 0 ds
# basen_of_int 16 26;;
- : string = "1a"
# basen_to_int 16 "1a";;
- : int = 26
</pre>
 
=={{header|PARI/GP}}==
let to_alpha_digit n =
<syntaxhighlight lang="parigp">toBase(n,b)={
if n < 10 then
my(s="",t);
char_of_int (n + int_of_char '0')
while(n,
else
t=n%b;
char_of_int (n + int_of_char 'a' - 10)
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);
for(i=1,#s,1,
t=b*t+s[i]-if(s[i]<58,48,87)
);
t
};</syntaxhighlight>
 
=={{header|Pascal}}==
let to_alpha_digits ds =
{{libheader| Math SysUtils}}
let buf = Buffer.create (List.length ds) in
{{works with|Free_Pascal}}
List.iter (fun i -> Buffer.add_char buf (to_alpha_digit i)) ds;
<syntaxhighlight lang="pascal">Program ConvertDemo(output);
Buffer.contents buf
 
uses
let from_alpha_digit c = match c with
Math, SysUtils;
'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
 
const
let from_alpha_digits s =
alphanum = '0123456789abcdefghijklmnopqrstuvwxyz';
let result = ref [] in
String.iter (fun c -> result := from_alpha_digit c :: !result) s;
List.rev !result</lang>
 
function ToDecimal(base: integer; instring: string): integer;
Example:
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;
<pre>
var
# to_alpha_digits (to_base 16 42);;
i, rem: integer;
- : string = "2a"
begin
# from_base 16 (from_alpha_digits "2a");;
ToBase :=' ';
- : int = 42
for i := 31 downto 1 do
</pre>
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.
</syntaxhighlight>
Output:
<pre>% ./Convert
1A: 26
26: 1a</pre>
 
=={{header|Perl}}==
For base 2 and 16, we can do this entirely with language features:
To parse from a base:
<syntaxhighlight lang="perl">sub to2 { sprintf "%b", shift; }
<lang perl>use POSIX;
sub to16 { sprintf "%x", shift; }
sub from2 { unpack("N", pack("B32", substr("0" x 32 . shift, -32))); }
sub from16 { hex(shift); }</syntaxhighlight>
 
Small functions will handle arbitrary base conversions for bases 2-36:
<syntaxhighlight lang="perl">sub base_to {
my($n,$b) = @_;
my $s = "";
do {
$s = ('0'..'9','a'..'z')[$n % $b] . $s
} while $n = int($n / $b);
$s
}
sub base_from {
my($n,$b) = @_;
my $t = 0;
for my $c (split(//, lc($n))) {
$t = $b * $t + index("0123456789abcdefghijklmnopqrstuvwxyz", $c);
}
$t;
}</syntaxhighlight>
 
There are a plethora of modules that perform base conversion.
 
The core [https://metacpan.org/pod/distribution/perl/ext/POSIX/lib/POSIX.pod POSIX] module includes strtol (and strtoul) which is simple and fast, but only does conversions from a base. On some platforms the function may be limited to 32-bit even with a 64-bit Perl.
<syntaxhighlight lang="perl">use POSIX;
my ($num, $n_unparsed) = strtol('1a', 16);
$n_unparsed == 0 or die "invalid characters found";
print "$num\n"; # prints "26"</langsyntaxhighlight>
 
The [https://metacpan.org/pod/ntheory ntheory] module includes functions that will perform base conversion, and is fast. It supports bases up to 36 and bigints.{{libheader|ntheory}}
To format into a base:
<syntaxhighlight lang="perl">use ntheory qw/fromdigits todigitstring/;
<lang perl>sub digitize
my $n = 65261;
# Converts an integer to a single digit.
{my $in16 = shifttodigitstring($n, 16) || 0;
my $n10 = fromdigits($n16, 16);
$i < 10
say "$n $n16 $n10"; # prints "65261 feed 65261"</syntaxhighlight>
? $i
: ('a' .. 'z')[$i - 10];}
 
Other modules include but are not limited to:
sub to_base
 
{my ($int, $radix) = @_;
* [https://metacpan.org/pod/Math::BaseCalc Math::BaseCalc]
my $numeral = '';
* [https://metacpan.org/pod/Math::Int2Base Math::Int2Base]
do {
* [https://metacpan.org/pod/Math::NumberBase Math::NumberBase]
$numeral .= digitize($int % $radix);
* [https://metacpan.org/pod/Convert::AnyBase Convert::AnyBase]
} while $int = int($int / $radix);
* [https://metacpan.org/pod/Math::BaseCnv Math::BaseCnv]
scalar reverse $numeral;}</lang>
* [https://metacpan.org/pod/Math::BaseConvert Math::BaseConvert]
 
The last two are ''much'' slower than the others or the simple functions above, but may have extra features. Math::Base::Convert and Convert::BaseN are currently not recommended.
 
The module [https://metacpan.org/pod/Math::Fleximal Math::Fleximal] not only does very arbitrary base conversion, but allows computations in different bases.
 
=={{header|Phix}}==
Phix itself handles number input in the expected decimal, or binary, octal, hexadecimal, and any base from 2 to 36 using prefixes 0b, 0o, 0x/X/#, and 0(2..36)<br>
The (s)printf() routine can generate strings in decimal, binary, octal, hexadecimal, or base 2-36|62, using %d/e/f/g, %b, %o, %x/X, %a|A formats respectively.<br>
The builtin to_number() function has an inbase parameter which defaults to 10 but can be 2..62.<br>
Note however that only decimal fractions are supported in the core language itself, and to_number(), and that (s)printf's %d..A are all integer-only, and %e/f/g decimal-only.<br>
Also note that 0t is(/was) an alternative for 0o (octal) on desktop/Phix, but not supported by JavaScript and hence pwa/p2js.<br>
mpz_set_str() and mpfr_set_str() can handle input strings expressed in decimal, binary (0b prefix), hexadecimal (0x prefix), or bases 2..62, including non-decimal fractions.<br>
mpz_get_str(), mpfr_get_str() [desktop/Phix only], and mpfr_get_fixed() can generate output strings in all bases 2..62.<br>
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #0000FF;">?{</span><span style="color: #000000;">26</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0b11010</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0o32</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0x1A</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0X1a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">#1A</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0(16)1A</span><span style="color: #0000FF;">}</span> <span style="color: #000080;font-style:italic;">-- displays {26,26,26,26,26,26,26}</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d == 0b%b == 0x%x\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">26</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays 26 == 0b11010 == 0x1A</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d == o(62)%A\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">26</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">62</span><span style="color: #0000FF;">,</span><span style="color: #000000;">26</span><span style="color: #0000FF;">}})</span> <span style="color: #000080;font-style:italic;">-- displays 26 == 0(62)Q</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">to_number</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1a"</span><span style="color: #0000FF;">,{},</span><span style="color: #000000;">16</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays 26</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">mpfr</span> <span style="color: #000000;">f</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpfr_init</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">mpfr_set_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"110.01"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"0b%s == %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">mpfr_get_fixed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">mpfr_get_fixed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">)})</span> <span style="color: #000080;font-style:italic;">-- 0b110.01 == 6.25</span>
<!--</syntaxhighlight>-->
The following (given the above not necessarily very useful) routines can handle simple integer conversions, in bases 2 to 36.<br>
You are expected to strip any leading "#" or "0x" from hexadecimal input strings (etc) manually, and (as-is) only use a-z not A-Z.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Convert_base.exw</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">to_base</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prepend</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">+</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;"><</span><span style="color: #000000;">10</span><span style="color: #0000FF;">?</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">:</span><span style="color: #008000;">'a'</span><span style="color: #0000FF;">-</span><span style="color: #000000;">10</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">/</span><span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"0"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">from_base</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">*</span><span style="color: #000000;">base</span><span style="color: #0000FF;">+(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">-</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;"><=</span><span style="color: #008000;">'9'</span><span style="color: #0000FF;">?</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">:</span><span style="color: #008000;">'a'</span><span style="color: #0000FF;">-</span><span style="color: #000000;">10</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">to_base</span><span style="color: #0000FF;">(</span><span style="color: #000000;">256</span><span style="color: #0000FF;">,</span><span style="color: #000000;">16</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">from_base</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"100"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">16</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
"100"
256
</pre>
 
=={{header|PHP}}==
PHP has a base_convert() function that directly converts between strings of one base and strings of another base:
<langsyntaxhighlight lang="php">base_convert("26", 10, 16); // returns "1a"</langsyntaxhighlight>
 
If you want to convert a string to an integer, the intval() function optionally takes a base argument when given a string:
<langsyntaxhighlight lang="php">intval("1a", 16); // returns 26</langsyntaxhighlight>
 
To go the other way around, I guess you can use base_convert() again; I am unaware of a better way:
<langsyntaxhighlight lang="php">base_convert(26, 10, 16); // returns "1a"</langsyntaxhighlight>
 
In addition, there are specialized functions for converting certain bases:
<langsyntaxhighlight lang="php">// converts int to binary string
decbin(26); // returns "11010"
// converts int to octal string
Line 780 ⟶ 2,877:
octdec("32"); // returns 26
// converts hex string to int
hexdec("1a"); // returns 26</langsyntaxhighlight>
 
=={{header|PL/I}}==
<lang PL/I>
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;
</lang>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de numToString (N Base)
(default Base 10)
(let L NIL
Line 820 ⟶ 2,901:
(prinl (numToString 26 16))
(prinl (stringToNum "1a" 16))
(prinl (numToString 123456789012345678901234567890 36))</langsyntaxhighlight>
Output:
<pre>"1a"
26
"byw97um9s91dlz68tsi"</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
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;
</syntaxhighlight>
 
=={{header|PL/M}}==
<syntaxhighlight lang="pli">100H:
 
/* CONVERT A NUMBER TO A GIVEN BASE */
TO$BASE: PROCEDURE (N, BASE, BUF) ADDRESS;
DECLARE (N, BUF, I, J, K) ADDRESS;
DECLARE (D, BASE, STR BASED BUF) BYTE;
/* GENERATE DIGITS */
I = 0;
DIGIT:
D = N MOD BASE;
N = N / BASE;
IF D < 10 THEN STR(I) = D + '0';
ELSE STR(I) = (D - 10) + 'A';
I = I + 1;
IF N > 0 THEN GO TO DIGIT;
/* PUT DIGITS IN HIGH-ENDIAN ORDER */
J = 0;
K = I-1;
DO WHILE (J < K);
D = STR(K);
STR(K) = STR(J);
STR(J) = D;
K = K-1;
J = J+1;
END;
STR(I) = '$';
RETURN BUF;
END TO$BASE;
 
 
/* READ A NUMBER IN A GIVEN BASE */
FROM$BASE: PROCEDURE (BUF, BASE) ADDRESS;
DECLARE (BUF, RESULT) ADDRESS;
DECLARE (D, BASE, CHAR BASED BUF) BYTE;
RESULT = 0;
DO WHILE CHAR <> '$';
D = CHAR - '0';
IF D >= 10 THEN D = D - ('A' - '0') + 10;
RESULT = (RESULT * BASE) + D;
BUF = BUF + 1;
END;
RETURN RESULT;
END FROM$BASE;
 
/* CP/M BDOS ROUTINES */
BDOS: PROCEDURE (F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
CRLF: PROCEDURE; CALL PRINT(.(13,10,'$')); END CRLF;
 
/* EXAMPLES */
DECLARE I BYTE, N ADDRESS;
 
CALL PRINT(.'1234 IN BASES 2-36: $'); CALL CRLF;
DO I=2 TO 36;
CALL PRINT(.'BASE $');
CALL PRINT(TO$BASE(I, 10, .MEMORY));
CALL PRINT(.(': ',9,'$'));
CALL PRINT(TO$BASE(1234, I, .MEMORY));
CALL CRLF;
END;
 
CALL PRINT(.'''25'' IN BASES 10-36: $'); CALL CRLF;
DO I=10 TO 36;
CALL PRINT(.'BASE $');
CALL PRINT(TO$BASE(I, 10, .MEMORY));
CALL PRINT(.(':',9,'$'));
N = FROM$BASE(.'25$', I);
CALL PRINT(TO$BASE(N, 10, .MEMORY));
CALL CRLF;
END;
 
CALL EXIT;
EOF</syntaxhighlight>
{{out}}
<pre style='height:50ex;'>1234 IN BASES 2-36:
BASE 2: 10011010010
BASE 3: 1200201
BASE 4: 103102
BASE 5: 14414
BASE 6: 5414
BASE 7: 3412
BASE 8: 2322
BASE 9: 1621
BASE 10: 1234
BASE 11: A22
BASE 12: 86A
BASE 13: 73C
BASE 14: 642
BASE 15: 574
BASE 16: 4D2
BASE 17: 44A
BASE 18: 3EA
BASE 19: 37I
BASE 20: 31E
BASE 21: 2GG
BASE 22: 2C2
BASE 23: 27F
BASE 24: 23A
BASE 25: 1O9
BASE 26: 1LC
BASE 27: 1IJ
BASE 28: 1G2
BASE 29: 1DG
BASE 30: 1B4
BASE 31: 18P
BASE 32: 16I
BASE 33: 14D
BASE 34: 12A
BASE 35: 109
BASE 36: YA
'25' IN BASES 10-36:
BASE 10: 25
BASE 11: 27
BASE 12: 29
BASE 13: 31
BASE 14: 33
BASE 15: 35
BASE 16: 37
BASE 17: 39
BASE 18: 41
BASE 19: 43
BASE 20: 45
BASE 21: 47
BASE 22: 49
BASE 23: 51
BASE 24: 53
BASE 25: 55
BASE 26: 57
BASE 27: 59
BASE 28: 61
BASE 29: 63
BASE 30: 65
BASE 31: 67
BASE 32: 69
BASE 33: 71
BASE 34: 73
BASE 35: 75
BASE 36: 77</pre>
 
=={{header|Pop11}}==
Line 835 ⟶ 3,077:
built-in procedures:
 
<langsyntaxhighlight lang="pop11">define number_to_base(n, base);
radix_apply(n, '%p', sprintf, base);
enddefine;</langsyntaxhighlight>
 
In input base optionally preceeds the number, for example
Line 843 ⟶ 3,085:
to prepend base prefix and read number from string:
 
<langsyntaxhighlight lang="pop11">define string_in_base_to_number(s, base);
incharitem(stringin(base >< ':' >< s))();
enddefine;</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">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</syntaxhighlight>
Sample output:
<pre>26
1a</pre>
 
=={{header|Python}}==
===Python: string to number===
<lang python>digits = "0123456789abcdefghijklmnopqrstuvwxyz"
Converting from string to number is straight forward:
def baseN(num,b):
<syntaxhighlight lang="python">i = int('1a',16) # returns the integer 26</syntaxhighlight>
return (((num == 0) and "0" )
or ( baseN(num // b, b).lstrip("0")
+ digits[num % b]))
 
===Python: number to string===
# alternatively:
Converting from number to string is harder:
def baseN(num,b):
;Recursive:
if num == 0: return "0"
result = ""
while num != 0:
num, d = divmod(num, b)
result += digits[d]
return result[::-1] # reverse
 
<syntaxhighlight lang="python">digits = "0123456789abcdefghijklmnopqrstuvwxyz"
k = 26
s =def baseN(knum,16 b) # returns the string 1a:
return digits[num] if num < b else baseN(num // b, b) + digits[num % b]</syntaxhighlight>
i = int('1a',16) # returns the integer 26</lang>
 
;Iterative:
=={{header|Ruby}}==
<lang ruby>s = 26.to_s(16) # returns the string 1a
i = '1a'.to_i(16) # returns the integer 26</lang>
Caution: <tt>to_i</tt> simply stops when it reaches an invalid character; it does not raise any exceptions. So sometimes it may appear to parse something and get a result, but it is only based on part of the input string:
<lang ruby>"59".to_i(7) # returns 5, but this is probably not what you wanted</lang>
 
<syntaxhighlight lang="python">digits = "0123456789abcdefghijklmnopqrstuvwxyz"
For a general base parsing that raises an exception for invalid characters:
 
def baseN(num, b):
{{trans|Tcl}}
result = []
<lang ruby>module BaseConvert
while num >= b:
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}
num, d = divmod(num, b)
result.append(digits[d])
result.append(digits[num])
return ''.join(result[::-1])</syntaxhighlight>
 
;Sample run from either:
def baseconvert(str, basefrom, baseto)
dec2base(base2dec(str, basefrom), baseto)
end
 
<pre>In [1: baseN(26, 16)
def base2dec(str, base)
Out[1]: '1a'</pre>
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
 
=={{header|Quackery}}==
def dec2base(n, base)
 
return "0" if n == 0
Handles radices in the range 2 to 36.
raise ArgumentError, "base is invalid" unless base.between?(2, DIGITS.length)
 
res = []
<syntaxhighlight lang="Quackery"> [ base put
while n > 0
number$
n, r = n.divmod(base)
base release
res.unshift(DIGITS[r])
end$ "" swap
res.join("")witheach
[ lower join ] ] is base_to_string ( n n --> $ )
 
[ base put
$->n drop
base release ] is string_to_base ( $ n --> n )</syntaxhighlight>
 
{{out}}
 
As a dialogue in the quackery shell.
 
<pre>/O> $ "sesquipedalian" 36 string_to_base
...
 
Stack: 4846409295160778886623
 
/O> 36 base_to_string echo$ cr
...
sesquipedalian
 
Stack empty.
</pre>
 
=={{header|R}}==
<syntaxhighlight lang="r">
 
 
int2str <- function(x, b) {
if(x==0) return("0")
if(x<0) return(paste0("-", base(-x,b)))
map <- c(as.character(0:9), letters)
res <- ""
while (x>0) {
res <- c(map[x %% b + 1], res)
x <- x %/% b
}
return(paste(res, collapse=""))
}
 
str2int <- function(s, b) {
map <- c(as.character(0:9), letters)
s <- strsplit(s,"")[[1]]
res <- sapply(s, function(x) which(map==x))
res <- as.vector((res-1) %*% b^((length(res)-1):0))
return(res)
}
 
## example: convert 255 to hex (ff):
int2str(255, 16)
 
## example: convert "1a" in base 16 to integer (26):
str2int("1a", 16)
 
</syntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
#lang racket
 
;; Both assume valid inputs
(define (num->str N r)
(let loop ([N N] [digits '()])
(define-values [N1 d] (quotient/remainder N r))
(define digits1 (cons (integer->char (+ d (if (< d 10) 48 55))) digits))
(if (zero? N) (list->string digits1) (loop N1 digits1))))
(define (str->num S r)
(for/fold ([N 0])
([B (string->bytes/utf-8 (string-upcase S))])
(+ (* N r) (- B (if (< 64 B) 55 48)))))
 
;; To try it out:
(define (random-test)
(define N (random 1000000))
(define r (+ 2 (random 35)))
(define S (num->str N r))
(define M (str->num S r))
(printf "~s -> ~a#~a -> ~a => ~a\n" N S r M (if (= M N) 'OK 'BAD)))
;; (random-test)
</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>sub from-base(Str $str, Int $base) {
+":$base\<$str>";
}
 
sub to-base(Real $num, Int $base) {
$num.base($base);
}</syntaxhighlight>
These work on any real type including integer types. There is also a build in method/function for Strings: [https://docs.raku.org/routine/parse-base parse-base].
 
=={{header|REXX}}==
Instead of writing two separate routines, only one was written to handle both tasks.
 
This routine was ripped out from a bigger version of mine that allowed any number as input, including decimal fractions (or whatever base).
 
Illegal numerals/digits are detected as well as illegal (or unsupported) bases.
 
No &nbsp; ''number-conversion'' &nbsp; BIFs &nbsp; (<u>B</u>uilt-<u>I</u>n <u>F</u>unctions) &nbsp; were used in this REXX program.
┌────────────────────────────────────────────────────────────────────┐
┌─┘ Input to this program (bases must be positive integers > 1): └─┐
│ │
│ x is required (it may have a sign). │
│ toBase the base to convert X to. │
│ inBase the base X is expressed in. │
│ │
│ If X has a leading sign, it is maintained (kept) after conversion. │
│ │
│ toBase or inBase can be a comma (,) which causes the default │
└─┐ of 10 to be used. The limits of bases are: 2 ──► 90. ┌─┘
└────────────────────────────────────────────────────────────────────┘
<syntaxhighlight lang="rexx">/*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</syntaxhighlight>
{{out|output|text=&nbsp; when input is expressed in hexadecimal &nbsp; (maximum positive integer in a signed 32-bit word): &nbsp; &nbsp; <tt> 7fffffff &nbsp; , &nbsp; 16 </tt>}}
<pre>
7fffffff (base 16) is 2147483647 (base 10)
</pre>
{{out|output|text=&nbsp; when input used (expressed in decimal) is: &nbsp; &nbsp; <tt> 4095 &nbsp; 2 </tt>}}
<pre>
4095 (base 10) is 111111111111 (base 2)
</pre>
{{out|output|text=&nbsp; when input used (expressed in binary) is: &nbsp; &nbsp; <tt> 100 &nbsp; 3 &nbsp; 2 </tt>}}
<pre>
100 (base 2) is 11 (base 3)
</pre>
{{out|output|text=&nbsp; when input used (expressed in base 62) is: &nbsp; &nbsp; <tt> zombiesAreEatingDeadVegetables &nbsp; 10 &nbsp; 62 </tt>}}
<pre>
zombiesAreEatingDeadVegetables (base 62) is 337500751396688020801073824403268172711989016896916476 (base 10)
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Non-decimal radices/Convert
 
see "0 (decimal) -> " + hex(0) + " (base 16)" + nl
see "26 (decimal) -> " + hex(26) + " (base 16)" + nl
see "383 (decimal) -> " + hex(383) + " (base 16)" + nl
see "26 (decimal) -> " + tobase(26, 2) + " (base 2)" + nl
see "383 (decimal) -> " + tobase(383, 2) + " (base 2)" + nl
see "1a (base 16) -> " + dec("1a") + " (decimal)" + nl
see "1A (base 16) -> " + dec("1A") + " (decimal)" + nl
see "17f (base 16) -> " + dec("17f") + " (decimal)" + nl
see "101111111 (base 2) -> " + bintodec("101111111") + " (decimal)" + nl
func tobase(nr, base)
binary = 0
i = 1
while(nr != 0)
remainder = nr % base
nr = floor(nr/base)
binary= binary + (remainder*i)
i = i*10
end
return string(binary)
func bintodec(bin)
binsum = 0
for n=1 to len(bin)
binsum = binsum + number(bin[n]) *pow(2, len(bin)-n)
next
return binsum
</syntaxhighlight>
Output:
<pre>
0 (decimal) -> 0 (base 16)
26 (decimal) -> 1a (base 16)
383 (decimal) -> 17f (base 16)
26 (decimal) -> 11010 (base 2)
383 (decimal) -> 101111111 (base 2)
1a (base 16) -> 26 (decimal)
1A (base 16) -> 26 (decimal)
17f (base 16) -> 383 (decimal)
101111111 (base 2) -> 383 (decimal)
</pre>
 
=={{header|RPL}}==
≪ → base
≪ "" SWAP
'''WHILE''' DUP '''REPEAT'''
base MOD LAST / FLOOR
SWAP DUP 9 > 87 48 IFTE + CHR
ROT + SWAP
'''END''' DROP
≫ ≫ ‘'''D→B'''’ STO
≪ → number base
≪ 0 1 number SIZE '''FOR''' j
base * number j DUP SUB
NUM DUP 57 > 87 48 IFTE - +
'''NEXT'''
≫ ≫ ‘'''B→D'''’ STO
 
"r0setta" 36 '''B→D'''
DUP 36 '''D→B'''
{{out}}
<pre>
2: 58820844142
1: "r0setta"
</pre>
 
=={{header|Ruby}}==
This converts strings from any base to any base up to base 36.
<syntaxhighlight lang="ruby">class String
def convert_base(from, to)
Integer(self, from).to_s(to)
# self.to_i(from).to_s(to) #if you don't want exceptions
end
end
 
# first three taken from TCL
include BaseConvert
p baseconvert("107h12345".convert_base(10, 23, 7) # => "50664107h"</lang>
p "107h".convert_base(23, 7) # =>"50664"
p "50664".convert_base(7, 10) # =>"12345"
p "1038334289300125869792154778345043071467300".convert_base(10, 36) # =>"zombieseatingdeadvegetables"
p "ff".convert_base(15, 10) # => ArgumentError</syntaxhighlight>
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">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</syntaxhighlight>
<table border=1>
<tr bgcolor=wheat align=center><td>Decimal</td><td>To Base</td><td>Num</td><td>to Dec</td></tr>
<tr align=right><td> 51</td><td> 2</td><td>110011</td><td>51</td></tr>
<tr align=right><td> 27</td><td> 10</td><td>27</td><td>27</td></tr>
<tr align=right><td> 12</td><td> 18</td><td>c</td><td>12</td></tr>
<tr align=right><td> 90</td><td> 35</td><td>2k</td><td>90</td></tr>
<tr align=right><td> 99</td><td> 17</td><td>5e</td><td>99</td></tr>
<tr align=right><td> 99</td><td> 18</td><td>59</td><td>99</td></tr>
<tr align=right><td> 55</td><td> 11</td><td>50</td><td>55</td></tr>
<tr align=right><td> 56</td><td> 28</td><td>20</td><td>56</td></tr>
<tr align=right><td> 71</td><td> 34</td><td>23</td><td>71</td></tr>
<tr align=right><td> 61</td><td> 23</td><td>2f</td><td>61</td></tr></table>
 
=={{header|Rust}}==
Rust standard library provides parsing a string in a given radix to all integer types.
There is no reverse operation (except for format specifiers for binary, octal, decimal
and hexadecimal base).
 
<syntaxhighlight lang="rust">fn format_with_radix(mut n: u32, radix: u32) -> String {
assert!(2 <= radix && radix <= 36);
 
let mut result = String::new();
 
loop {
result.push(std::char::from_digit(n % radix, radix).unwrap());
n /= radix;
if n == 0 {
break;
}
}
 
result.chars().rev().collect()
}
 
#[cfg(test)]
#[test]
fn test() {
for value in 0..100u32 {
for radix in 2..=36 {
let s = format_with_radix(value, radix);
let v = u32::from_str_radix(s.as_str(), radix).unwrap();
assert_eq!(value, v);
}
}
}
 
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("{}", format_with_radix(0xdeadbeef, 2));
println!("{}", format_with_radix(0xdeadbeef, 36));
println!("{}", format_with_radix(0xdeadbeef, 16));
println!("{}", u32::from_str_radix("DeadBeef", 16)?);
Ok(())
}</syntaxhighlight>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">def backToBig(num: String, oldBase: Int): BigInt = BigInt(num, oldBase)
 
def bigToBase(num: BigInt, newBase: Int): String = num.toString(newBase)</syntaxhighlight>
 
=={{header|Scheme}}==
R7RS specifies only a radix of 2, 8, 10, or 16 for the functions below. However, some implementations support arbitrary (e.g. Chibi-Scheme or Guile).
<syntaxhighlight lang="scheme">
(number->string 26 16)
 
(string->number "1a" 16)</syntaxhighlight>
 
=={{header|Seed7}}==
The type [http://seed7.sourceforge.net/manual/types.htm#integer integer]
defines the operator [http://seed7.sourceforge.net/libraries/integer.htm#%28in_integer%29radix%28in_integer%29 radix]
and the function [http://seed7.sourceforge.net/libraries/integer.htm#integer%28in_string,in_integer%29 integer],
which convert to string and vice versa.
The type [http://seed7.sourceforge.net/manual/types.htm#bigInteger bigInteger]
defines [http://seed7.sourceforge.net/libraries/bigint.htm#%28in_var_bigInteger%29radix%28in_integer%29 radix]
and [http://seed7.sourceforge.net/libraries/bigint.htm#bigInteger%28in_string,in_integer%29 bigInteger]
for corresponding purposes.
 
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
const proc: main is func
begin
writeln(60272032366_ radix 36); # Convert bigInteger to string
writeln(591458 radix 36); # Convert integer to string
 
writeln(bigInteger("rosetta", 36)); # Convert string to bigInteger
writeln(integer("code", 36)); # Convert string to integer
end func;</syntaxhighlight>
 
{{out}}
<pre>
rosetta
code
60272032366
591458
</pre>
 
=={{header|Sidef}}==
Built-in:
<syntaxhighlight lang="ruby">say 60272032366.base(36) # convert number to string
say Number("rosetta", 36) # convert string to number</syntaxhighlight>
 
User-defined:
{{trans|Perl}}
<syntaxhighlight lang="ruby">static to = [@|'0'..'9', @|'a'..'z']
static from = Hash(to.pairs.map{@|_}.flip...)
 
func base_to(n, b) {
var s = ""
while (n) {
s += to[n % b]
n //= b
}
s.reverse
}
 
func base_from(n, b) {
var t = 0
n.each { |c| t = (b*t + from{c}) }
t
}
 
say base_from("rosetta", 36) # string to number
say base_to(60272032366, 36) # number to string</syntaxhighlight>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">26 printString &radix: 16
Integer readFrom: '1A' &radix: 16.</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<syntaxhighlight lang="smalltalk">26 printStringRadix:16 -> '1A'
Integer readFrom:'1A' radix:16 -> 26
 
2 to:36 do:[:radix |
'radix %2d: %s\n' printf:{radix . 100 printStringRadix:radix } on:Transcript.
].
</syntaxhighlight>
{{out}}
<pre>radix 2: 1100100
radix 3: 10201
radix 4: 1210
radix 5: 400
radix 6: 244
radix 7: 202
radix 8: 144
radix 9: 121
radix 10: 100
radix 11: 91
radix 12: 84
radix 13: 79
radix 14: 72
radix 15: 6A
radix 16: 64
radix 17: 5F
radix 18: 5A
radix 19: 55
radix 20: 50
radix 21: 4G
radix 22: 4C
radix 23: 48
radix 24: 44
radix 25: 40
radix 26: 3M
radix 27: 3J
radix 28: 3G
radix 29: 3D
radix 30: 3A
radix 31: 37
radix 32: 34
radix 33: 31
radix 34: 2W
radix 35: 2U
radix 36: 2S</pre>
 
=={{header|Standard ML}}==
{{trans|Haskell}}
 
<langsyntaxhighlight lang="sml">fun toBase b v = let
fun toBase' (a, 0) = a
| toBase' (a, v) = toBase' (v mod b :: a, v div b)
Line 940 ⟶ 3,650:
in
map convert o explode
end</langsyntaxhighlight>
 
Example:
Line 951 ⟶ 3,661:
val it = 42 : int
</pre>
 
=={{header|Swift}}==
Converting integer to string:
<syntaxhighlight lang="swift">println(String(26, radix: 16)) // prints "1a"</syntaxhighlight>
 
Converting string to integer:
<syntaxhighlight lang="swift">import Darwin
func string2int(s: String, radix: Int) -> Int {
return strtol(s, nil, Int32(radix))
// there is also strtoul() for UInt, and strtoll() and strtoull() for Int64 and UInt64, respectively
}
println(string2int("1a", 16)) // prints "26"</syntaxhighlight>
 
=={{header|Tcl}}==
Tcl <code>scan</code> and <code>format</code> commands can convert between decimal, octal and hexadecimal, but this solution can convert between any arbitrary bases.
<langsyntaxhighlight lang="tcl">namespace eval baseconvert {
variable chars "0123456789abcdefghijklmnopqrstuvwxyz"
namespace export baseconvert
Line 981 ⟶ 3,703:
baseconvert 12345 10 23 ;# ==> 107h
baseconvert 107h 23 7 ;# ==> 50664
baseconvert 50664 7 10 ;# ==> 12345</langsyntaxhighlight>
 
=={{header|Ursala}}==
A function parameterized by the base b performs the conversion in each direction.
Folding (=>), iteration (->), and reification (-:) operators among others are helpful.
<langsyntaxhighlight Ursalalang="ursala">#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"</langsyntaxhighlight>
This test program performs the conversions in both directions for a selection of numbers
in base 8 and base 32.
<langsyntaxhighlight Ursalalang="ursala">test_data = <1,2,15,32,100,65536,323498993>
 
#cast %sLnLUL
Line 1,004 ⟶ 3,726:
string_to_num32* num_to_string32* test_data,
num_to_string8* test_data,
string_to_num8* num_to_string8* test_data></langsyntaxhighlight>
output:
<pre>
Line 1,012 ⟶ 3,734:
<'1','2','17','40','144','200000','2322031761'>,
<1,2,15,32,100,65536,323498993>></pre>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">Private Function to_base(ByVal number As Long, base As Integer) As String
Dim digits As String, result As String
Dim i As Integer, digit As Integer
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
Do While number > 0
digit = number Mod base
result = Mid(digits, digit + 1, 1) & result
number = number \ base
Loop
to_base = result
End Function
Private Function from_base(number As String, base As Integer) As Long
Dim digits As String, result As Long
Dim i As Integer
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)
For i = 2 To Len(number)
result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)
Next i
from_base = result
End Function
Public Sub Non_decimal_radices_Convert()
Debug.Print "26 decimal in base 16 is: "; to_base(26, 16); ". Conversely, hexadecimal 1a in decimal is: "; from_base("1a", 16)
End Sub</syntaxhighlight>{{out}}<pre>26 decimal in base 16 is: 1a. Conversely, hexadecimal 1a in decimal is: 26 </pre>
 
=={{header|Wolframalpha}}==
input box: 1801 decimal to base 16<br>
input box: (99 base 12)+(77 base 8)<br>
This is Mathematica but is worth showing distinctly. Result provides endian choice and other bases typically.
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
The methods Conv.itoa and Conv.atoi in the above module provide the required functionality.
<syntaxhighlight lang="wren">import "./fmt" for Conv
 
System.print(Conv.itoa(26, 16))
System.print(Conv.atoi("1a", 16))</syntaxhighlight>
 
{{out}}
<pre>
1a
26
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">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);
]</syntaxhighlight>
 
Output:
<pre>
0
1a
1111111111111111111111111111111
4
26
-559038737
</pre>
 
=={{header|zkl}}==
The toInt(base) and toString(base) methods do this. base is 2..36
<syntaxhighlight lang="zkl">(26).toString(16) //--> "1a"
"1a".toInt(16) //-->26</syntaxhighlight>
In addition, string format is able to convert to a base:
<syntaxhighlight lang="zkl">"%x %,.2B".fmt(26,26) //-->"1a 1|1010"</syntaxhighlight>
 
 
[[Category:Radices]]
3

edits