Non-decimal radices/Convert: Difference between revisions

no edit summary
(Reduce the Rust code)
No edit summary
 
(33 intermediate revisions by 20 users not shown)
Line 17:
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}}==
<langsyntaxhighlight Lisplang="lisp">(defun digit-value (chr)
(cond ((and (char>= chr #\0)
(char<= chr #\9))
Line 53 ⟶ 77:
 
(defun show-num (num base)
(coerce (reverse (num-to-cs num base)) 'string))</langsyntaxhighlight>
 
=={{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 110 ⟶ 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}}==
<langsyntaxhighlight lang="aime">o_text(bfxa(0, 0, 16, 1000000));
o_byte('\n');
o_text(bfxa(0, 0, 5, 1000000));
Line 125 ⟶ 246:
o_byte('\n');
o_integer(alpha("11110100001001000000", 2));
o_byte('\n');</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 137 ⟶ 258:
a numbers base.
 
<langsyntaxhighlight lang="algol68">INT base = 16, from dec = 26;
BITS to bits;
 
Line 150 ⟶ 271:
reset(f);
getf(f, (hex repr, to bits));
print(("Int: ",ABS to bits, new line))</langsyntaxhighlight>
Output:
<pre>
Line 167 ⟶ 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 202 ⟶ 323:
INT i = int(s,16); # returns the integer 26 #
print((k," => ", s, " => ", i, new line))
OD</langsyntaxhighlight>
Output:
<pre>
Line 219 ⟶ 340:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight 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 %
Line 284 ⟶ 405:
write( 35, i, baseNumber, " ", convertFromBase( baseNumber, i ) );
end
end.</langsyntaxhighlight>
 
=={{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:
<langsyntaxhighlight AppleScriptlang="applescript">-- toBase :: Int -> Int -> String
on toBase(intBase, n)
if (intBase < 36) and (intBase > 0) then
Line 384 ⟶ 505:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{{{binary:"11111111", octal:"377", hex:"ff"}, {upperHex:"FF", dgDecimal:"२५५"}},
{{binary:"11110000", octal:"360", hex:"f0"}, {upperHex:"F0", dgDecimal:"२४०"}}}</langsyntaxhighlight>
 
=={{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 414 ⟶ 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 428 ⟶ 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 458 ⟶ 635:
print strtol("7b", 16)
print ltostr(123, 16)
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight 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)"
Line 488 ⟶ 665:
A$ = MID$(A$,2)
UNTIL A$ = ""
= N%</langsyntaxhighlight>
'''Output:'''
<pre>
Line 501 ⟶ 678:
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}}==
<langsyntaxhighlight lang="bracmat"> ( display
=
. !arg:<10
Line 525 ⟶ 824:
& get$:~/#>1:~>36:?b
& out$(!n " in base " !b " is " str$(base$(!n.!b)))
);</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <string.h>
#include <stdio.h>
Line 575 ⟶ 874:
printf("%lld in base 16: %s\n", x, to_base(x, 16));
return 0;
}</langsyntaxhighlight>output
<pre>-9223372036854775808 in base 2: -1000000000000000000000000000000000000000000000000000000000000000
383 in base 16: 17f</pre>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">
<lang CSharp>
public static class BaseConverter {
 
Line 709 ⟶ 1,008:
 
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <string>
#include <cstdlib>
#include <algorithm>
Line 740 ⟶ 1,039:
result = result * base + digits.find(num_str[pos]);
return result;
}</langsyntaxhighlight>
 
=={{header|Caché ObjectScript}}==
 
<langsyntaxhighlight lang="cos">Class Utils.Number [ Abstract ]
{
 
Line 810 ⟶ 1,109:
}
 
}</langsyntaxhighlight>
{{out|Examples}}
<pre>
Line 832 ⟶ 1,131:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(parse-integer "1a" :radix 16) ; returns multiple values: 26, 2
(write-to-string 26 :base 16) ; also "1A"</langsyntaxhighlight>
 
Alternative implementation using FORMAT's ~R directive and #nR reader macro
<langsyntaxhighlight 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)))</langsyntaxhighlight>
 
Yet another approach uses FORMAT's ~R in conjunction with ~V for passing arguments to directives (this assumes input as string)
<langsyntaxhighlight lang="lisp">(defun change-base (number input-base output-base)
(format nil "~vr" output-base (parse-integer number :radix input-base)))</langsyntaxhighlight>
 
=={{header|D}}==
===Using Standard Functions===
<langsyntaxhighlight lang="d">import std.stdio, std.conv, std.string, std.ascii;
 
void main() {
Line 855 ⟶ 1,154:
writeln(60_272_032_366.to!string(36, LetterCase.lower), ' ',
591_458.to!string(36, LetterCase.lower));
}</langsyntaxhighlight>
{{out}}
<pre>109517
Line 861 ⟶ 1,160:
 
===One Implementation===
<langsyntaxhighlight lang="d">import std.stdio, std.array, std.ascii;
 
immutable string mDigits = digits ~ lowercase;
Line 922 ⟶ 1,221:
writeln(itoaRadix(60_272_032_366, 36), " ",
itoaRadix(591_458, 36));
}</langsyntaxhighlight>
{{out}}
<pre>'1ABcdxyz???' (base 16) = 109517 Converted only: '1ABcd'
Line 929 ⟶ 1,228:
===Alternative Implementation===
{{trans|Haskell}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.ascii, std.array, std.string;
 
alias Digits = ubyte[];
Line 958 ⟶ 1,257:
void main() {
"1ABcd".toDigits.fromBase(16).writeln;
}</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight 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</langsyntaxhighlight>
 
=={{header|Erlang}}==
Line 993 ⟶ 1,402:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function to_base(integer i, integer base)
integer rem
sequence s
Line 1,027 ⟶ 1,436:
end for
return i
end function</langsyntaxhighlight>
 
=={{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 1,094 ⟶ 1,503:
WRITE (*,*) ToBase(16, 26)
 
END PROGRAM</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function min(x As Integer, y As Integer) As Integer
Line 1,152 ⟶ 1,561:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,195 ⟶ 1,604:
=={{header|FunL}}==
Converting from integer to string:
<langsyntaxhighlight lang="funl">$stdout = int( '1a', 16 )</langsyntaxhighlight>
 
{{out}}
Line 1,204 ⟶ 1,613:
 
Converting from string to integer:
<langsyntaxhighlight lang="funl">$stdout = str( 26, 16 )</langsyntaxhighlight>
 
{{out}}
Line 1,219 ⟶ 1,628:
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
(binary <code>%b</code>, octal <code>%o</code>, decimal <code>%d</code>, and hexidecimal <code>%x</code> or <code>%X</code>).
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,239 ⟶ 1,648:
fmt.Println(b)
}
}</langsyntaxhighlight>
 
=={{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 1,257 ⟶ 1,666:
assert valM2str == biggestDigit + biggestDigit
printf ("%3s (%2d) - 2 (10) == %4s (%2d)\n", numString, radix, valM2str, radix)
}</langsyntaxhighlight>
 
Output:
Line 1,335 ⟶ 1,744:
Using built-in functions to convert integer into string, and vice versa, at any base up to 16:
 
<langsyntaxhighlight lang="haskell">Prelude> Numeric.showIntAtBase 16 Char.intToDigit 42 ""
"2a"
Prelude> fst $ head $ Numeric.readInt 16 Char.isHexDigit Char.digitToInt "2a"
42</langsyntaxhighlight>
 
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 1,344 ⟶ 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 1,364 ⟶ 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>
 
 
Line 1,378 ⟶ 1,787:
If we want to assume a default character set, then a general '''toBase''' (Int -> Int -> String) can be also be derived from '''inBaseDigits'''.
 
<langsyntaxhighlight lang="haskell">import Data.Bifunctor (first)
import Data.List (unfoldr)
import Data.Tuple (swap)
Line 1,431 ⟶ 1,840:
, inHinduArabicDecimal
] <*>
[254]</langsyntaxhighlight>
 
{{Out}}
Line 1,444 ⟶ 1,853:
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">CHARACTER txt*80
 
num = 36^7 -1 ! 7836416410
Line 1,471 ⟶ 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.
 
<langsyntaxhighlight Iconlang="icon">procedure main()
every ( ns := "16r5a" | "-12r1a" ) &
( b := 8 | 12 | 16 ) do {
Line 1,502 ⟶ 1,911:
return p || reverse(s)
}
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 1,517 ⟶ 1,926:
=={{header|J}}==
J supports direct specification of native 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 10b_100 16b100 36b100 36bzy
4 64 _100 256 1296 1294</langsyntaxhighlight>
 
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.
 
Here are programs for conversion of numeric values to literals, and of literals to numbers:
<langsyntaxhighlight lang="j">numerals=: '0123456789abcdefghijklmnopqrstuvwxyz'
baseNtoL=: numerals {~ #.inv
baseLtoN=: [ #. numerals i. ]</langsyntaxhighlight>
Examples of use:
<langsyntaxhighlight lang="j"> 2 baseNtoL 100 101
1100100
1100101
Line 1,533 ⟶ 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 1,551 ⟶ 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 1,560 ⟶ 1,969:
public static String tenBigToBase(BigInteger num, int newBase){
return num.toString(newBase);//add .toUpperCase() for capital letters
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight 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.
<langsyntaxhighlight lang="javascript">
var baselist = "0123456789abcdefghijklmnopqrstuvwxyz", listbase = [];
for(var i = 0; i < baselist.length; i++) listbase[baselist[i]] = i; // Generate baselist reverse
Line 1,592 ⟶ 2,001:
return to.join('');
}
console.log("Result:", basechange("zzzzzzzzzz", 36, 10));</langsyntaxhighlight>
Using BigInteger, can convert any base.
<langsyntaxhighlight lang="javascript">
// Tom Wu jsbn.js http://www-cs-students.stanford.edu/~tjw/jsbn/
var baselist = "0123456789abcdefghijklmnopqrstuvwxyz", listbase = [];
Line 1,623 ⟶ 2,032:
return to.join('');
}
</syntaxhighlight>
</lang>
 
===ES6===
Line 1,629 ⟶ 2,038:
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.
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,721 ⟶ 2,130:
devanagariDecimal: inDevanagariDecimal(n)
}));
})();</langsyntaxhighlight>
 
{{Out}}
Line 1,739 ⟶ 2,148:
"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}}==
<langsyntaxhighlight lang="jq"># Convert the input integer to a string in the specified base (2 to 36 inclusive)
def convert(base):
def stream:
recurse(if . >= 0base then ./base|floor else empty end) | . % base ;
[stream] | reverse
if . == 0 then "0"
else [stream] | reverse | .[1:]
| 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;
end;
 
# input string is converted from "base" to an integer, within limits
Line 1,762 ⟶ 2,184:
# state: [power, ans]
([1,0]; (.[0] * base) as $b | [$b, .[1] + (.[0] * $c)])
| .[1];</langsyntaxhighlight>
'''Example''':
<langsyntaxhighlight lang="jq">(255 | convert(16)),
("ff" | to_i(16)),
("10" | to_i(10))</langsyntaxhighlight>
{{Out}}
$jq -M -r -n -f Non-decimal_radices.jq
Line 1,774 ⟶ 2,196:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">
#@show 26 instring(185, base 16 or =2)
@show string(185, base=3)
base(16, 26)
@show string(185, base=4)
base(2, 26)
@show string(185, base=5)
 
@show string(185, base=6)
# Parse to integer
@show string(185, base=7)
parse(Int, "1a", 16)
@show string(185, base=8)
parse(Int, "101101", 2)
@show string(185, base=9)
</lang>
@show string(185, base=10)
 
@show string(185, base=11)
{{out}}
@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"
"1a"
string(185, base = 3) = "20212"
"11010"
string(185, base = 4) = "2321"
26
string(185, base = 5) = "1220"
45
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>
 
Line 1,795 ⟶ 2,234:
An approach from first principles rather than using Java library functions:
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun min(x: Int, y: Int) = if (x < y) x else y
Line 1,839 ⟶ 2,278:
println("36 base $f = ${s.padEnd(6)} -> base $f = ${convertToDecimal(s, b)}")
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,883 ⟶ 2,322:
 
Converting decimal numbers 26 and 3000 in LFE, using some different mechanisms:
<langsyntaxhighlight lang="lisp">
> (: erlang list_to_integer '"1a" 16)
26
Line 1,896 ⟶ 2,335:
> (: erlang integer_to_list 3000 2)
"101110111000"
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb"> ' Base Converter v6
 
global alphanum$
Line 1,931 ⟶ 2,370:
next i
end function
</langsyntaxhighlight>
 
=={{header|Lua}}==
Only had to write 'dec2base' as the reverse is provided by the in-built function 'tonumber'
<langsyntaxhighlight Lualang="lua">function dec2base (base, n)
local result, digit = ""
while n > 0 dorepeat
local digit = n % base
if digit > 9 then digit = string.char(digit + 87) end
n digit = mathstring.floorchar(ndigit /+ base87)
end
result = digit .. result
n = n // base
end
until n == 0
return result
end
Line 1,948 ⟶ 2,389:
local x = dec2base(16, 26)
print(x) --> 1a
print(tonumber(x, 16)) --> 26</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
k$=lambda$ (m, b as integer=16) -> {
Line 1,978 ⟶ 2,419:
}
Checkit
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,992 ⟶ 2,433:
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">eval(26,16)
define(`frombase',`eval(0r$2:$1)')
frombase(1a,16)</langsyntaxhighlight>
 
Output:
Line 2,004 ⟶ 2,445:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">#converts a number to a given based represented by a string
to_base := proc(num, based)
local i;
Line 2,034 ⟶ 2,475:
end do;
return result;
end proc:</langsyntaxhighlight>
{{Out|Usage}}
<pre>
Line 2,050 ⟶ 2,491:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Use the built-in functions IntegerString[] and FromDigits[]:
<langsyntaxhighlight Mathematicalang="mathematica">IntegerString[26,16]
FromDigits["1a", 16])</langsyntaxhighlight>
{{out}}
 
Output:
<pre>"1a"
 
26</pre>
 
=={{header|MATLAB}} / {{header|Octave}}==
Use the built-in functions base2dec() and dec2base():
<langsyntaxhighlight Matlablang="matlab">dec2base(26,16)
base2dec('1a', 16)</langsyntaxhighlight>
 
Output:
Line 2,088 ⟶ 2,527:
=={{header|NetRexx}}==
In NetRexx numbers are held as Rexx strings so you can take advantage of Java's BigInteger to do radix conversions.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,127 ⟶ 2,566:
bi = BigInteger(val.toString(), 10)
return bi.toString(radix)
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 2,153 ⟶ 2,592:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils
 
proc reverse(a: string): string =
Line 2,178 ⟶ 2,617:
 
for i in first .. str.high:
let c = str[i].toLowertoLowerAscii
assert c in digits[0 .. < base]
result = result * base + digits.find c
 
Line 2,185 ⟶ 2,624:
 
echo 26.toBase 16
echo "1a".fromBase 16</langsyntaxhighlight>
Output:
<pre>1a
Line 2,191 ⟶ 2,630:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let int_of_basen n str =
match n with
| 16 -> int_of_string("0x" ^ str)
Line 2,202 ⟶ 2,641:
| 16 -> Printf.sprintf "%x" d
| 8 -> Printf.sprintf "%o" d
| _ -> failwith "unhandled"</langsyntaxhighlight>
 
# basen_of_int 16 26 ;;
Line 2,210 ⟶ 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
 
let from_base b ds =
List.fold_left (fun n k -> n * b + k) 0 ds
 
let to_alpha_digit n =
if n < 10 then
char_of_int (n + int_of_char '0')
else
char_of_int (n + int_of_char 'a' - 10)
 
let to_alpha_digits ds =
let buf = Buffer.create (List.length ds) in
List.iter (fun i -> Buffer.add_char buf (to_alpha_digit i)) ds;
Buffer.contents buf
 
let from_alpha_digit c = match c with
'0'..'9' -> int_of_char c - int_of_char '0'
| 'A'..'Z' -> int_of_char c - int_of_char 'A' + 10
| 'a'..'z' -> int_of_char c - int_of_char 'a' + 10
 
let from_alpha_digits s =
let result = ref [] in
String.iter (fun c -> result := from_alpha_digit c :: !result) s;
List.rev !result</lang>
 
Example:
 
<pre>
# to_alpha_digits (to_basebasen_of_int 16 42)26;;
- : string = "2a1a"
# from_basebasen_to_int 16 (from_alpha_digits "2a1a");;
- : int = 4226
</pre>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">toBase(n,b)={
my(s="",t);
while(n,
Line 2,271 ⟶ 2,694:
);
t
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{libheader| Math SysUtils}}
{{works with|Free_Pascal}}
<langsyntaxhighlight lang="pascal">Program ConvertDemo(output);
 
uses
Line 2,321 ⟶ 2,744:
writeln ('26: ', ToBase(16, 26));
end.
</syntaxhighlight>
</lang>
Output:
<pre>% ./Convert
Line 2,329 ⟶ 2,752:
=={{header|Perl}}==
For base 2 and 16, we can do this entirely with language features:
<langsyntaxhighlight lang="perl">sub to2 { sprintf "%b", shift; }
sub to16 { sprintf "%x", shift; }
sub from2 { unpack("N", pack("B32", substr("0" x 32 . shift, -32))); }
sub from16 { hex(shift); }</langsyntaxhighlight>
 
Small functions will handle arbitrary base conversions for bases 2-36:
<langsyntaxhighlight lang="perl">sub base_to {
my($n,$b) = @_;
my $s = "";
while ($n)do {
$s .= ('0'..'9','a'..'z')[$n % $b]; . $s
} while $n = int($n / $b);
}$s
scalar(reverse($s));
}
sub base_from {
Line 2,351 ⟶ 2,773:
}
$t;
}</langsyntaxhighlight>
 
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.
<langsyntaxhighlight 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}}
<langsyntaxhighlight lang="perl">use ntheory qw/fromdigits todigitstring/;
my $n = 65261;
my $n16 = todigitstring($n, 16) || 0;
my $n10 = fromdigits($n16, 16);
say "$n $n16 $n10"; # prints "65261 feed 65261"</langsyntaxhighlight>
 
Other modules include but are not limited to:
Line 2,382 ⟶ 2,804:
 
=={{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/t/, 0x/X/#, and 0(2..36)<br>
The (s)printf() routine can generate strings in decimal, binary, octal, hexadecimal, or hexadecimalbase 2-36|62, using %d/e/f/g, %b, %o/t, %x/X, %a|A formats respectively.<br>
The builtin to_number() function has an inbase parameter which defaults to 10 but can be 2..1662.<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>
mpz_set_str() and mpfr_set_str() can handle input strings expressed in decimal, binary (0b prefix), or hexadecimal (0x prefix).<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_get_str() and mpfr_get_str() can generate output strings in all bases 2..62.
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>
<lang Phix>?{26,0b11010,0o32,0t32,0x1A,0X1a,#1A,0(16)1A} -- displays {26,26,26,26,26,26,26,26}
mpz_get_str(), mpfr_get_str() [desktop/Phix only], and mpfr_get_fixed() can generate output strings in all bases 2..62.<br>
printf(1,"%d == 0b%b == 0x%x\n",26) -- displays 26 == 0b11010 == 0x1A
<!--<syntaxhighlight lang="phix">(phixonline)-->
?to_number("1a",{},16) -- displays 26</lang>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
The following routines can handle all other conversions, in bases 2 to 36. <br>
<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>
Note 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.
<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>
<lang Phix>-- demo\rosetta\Convert_base.exw
<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>
function to_base(integer i, integer base)
<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>
integer c
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
sequence s = ""
<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>
while i>0 do
<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>
c = remainder(i,base)
<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>
if c<10 then
<!--</syntaxhighlight>-->
c += '0'
The following (given the above not necessarily very useful) routines can handle simple integer conversions, in bases 2 to 36.<br>
else
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.
c += 'a'-10
<!--<syntaxhighlight lang="phix">(phixonline)-->
end if
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Convert_base.exw</span>
s = prepend(s,c)
<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>
i = floor(i/base)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
end while
<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>
if length(s) = 0 then
<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>
s = "0"
<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>
end if
<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>
return s
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function from_base(string s, integer base)
<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>
integer res = 0, c
<span style="color: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
for i=1 to length(s) do
<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>
c = s[i]
<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>
if c>='0' and c<='9' then
<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>
c -= '0'
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
else
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
c -= 'a'-10
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
end if
res = res*base+c
<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>
end for
<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>
return res
<!--</syntaxhighlight>-->
end function
 
?to_base(256,16)
?from_base("100",16)</lang>
{{out}}
<pre>
Line 2,438 ⟶ 2,857:
=={{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 2,458 ⟶ 2,877:
octdec("32"); // returns 26
// converts hex string to int
hexdec("1a"); // returns 26</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de numToString (N Base)
(default Base 10)
(let L NIL
Line 2,482 ⟶ 2,901:
(prinl (numToString 26 16))
(prinl (stringToNum "1a" 16))
(prinl (numToString 123456789012345678901234567890 36))</langsyntaxhighlight>
Output:
<pre>"1a"
Line 2,489 ⟶ 2,908:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
convert: procedure (N, base) returns (character (64) varying) recursive;
declare N fixed binary (31), base fixed binary;
Line 2,502 ⟶ 2,921:
return (s || table(mod(N, base)) );
end convert;
</syntaxhighlight>
</lang>
 
=={{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 2,513 ⟶ 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 2,521 ⟶ 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}}==
<langsyntaxhighlight PureBasiclang="purebasic">Global alphanum$ = "0123456789abcdefghijklmnopqrstuvwxyz" ;36 digits
#maxIntegerBitSize = SizeOf(Integer) * 8
Line 2,561 ⟶ 3,125:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>26
Line 2,569 ⟶ 3,133:
===Python: string to number===
Converting from string to number is straight forward:
<langsyntaxhighlight lang="python">i = int('1a',16) # returns the integer 26</langsyntaxhighlight>
 
===Python: number to string===
Line 2,575 ⟶ 3,139:
;Recursive:
 
<langsyntaxhighlight lang="python">digits = "0123456789abcdefghijklmnopqrstuvwxyz"
def baseN(num, b):
return (((digits[num] ==if 0)num and< b "0"else baseN(num // b, b) + digits[num % b]</syntaxhighlight>
or ( baseN(num // b, b).lstrip("0")
+ digits[num % b]))</lang>
 
;Iterative:
 
<syntaxhighlight lang="python">digits = [[ch] for ch in "0123456789abcdefghijklmnopqrstuvwxyz"]
 
def baseN(num, b):
if num == 0:
return "0"
result = []
while num !>= 0b:
num, d = divmod(num, b)
result += .append(digits[d])
return ''result.joinappend(resultdigits[::-1num])</lang>
return ''.join(result[::-1])</syntaxhighlight>
 
;Sample run from either:
Line 2,598 ⟶ 3,159:
<pre>In [1: baseN(26, 16)
Out[1]: '1a'</pre>
 
=={{header|Quackery}}==
 
Handles radices in the range 2 to 36.
 
<syntaxhighlight lang="Quackery"> [ base put
number$
base release
$ "" swap
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">
<lang R>
 
 
Line 2,630 ⟶ 3,222:
str2int("1a", 16)
 
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 2,656 ⟶ 3,248:
(printf "~s -> ~a#~a -> ~a => ~a\n" N S r M (if (= M N) 'OK 'BAD)))
;; (random-test)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub from-base(Str $str, Int $base) {
+":$base\<$str>";
}
Line 2,666 ⟶ 3,258:
sub to-base(Real $num, Int $base) {
$num.base($base);
}</langsyntaxhighlight>
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}}==
Line 2,689 ⟶ 3,281:
└─┐ of 10 to be used. The limits of bases are: 2 ──► 90. ┌─┘
└────────────────────────────────────────────────────────────────────┘
<langsyntaxhighlight 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. */
Line 2,725 ⟶ 3,317:
erd: call ser 'illegal digit/numeral ['?"] in: " x
erm: call ser 'no argument specified.'
ser: say; say '***error!***'; say arg(1); exit 13</langsyntaxhighlight>
{{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>
Line 2,744 ⟶ 3,336:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Non-decimal radices/Convert
 
Line 2,774 ⟶ 3,366:
next
return binsum
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,786 ⟶ 3,378:
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.
<langsyntaxhighlight lang="ruby">class String
def convert_base(from, to)
Integer(self, from).to_s(to)
Line 2,802 ⟶ 3,419:
p "50664".convert_base(7, 10) # =>"12345"
p "1038334289300125869792154778345043071467300".convert_base(10, 36) # =>"zombieseatingdeadvegetables"
p "ff".convert_base(15, 10) # => ArgumentError</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight 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>"
Line 2,832 ⟶ 3,449:
toDecimal = toDecimal * b + instr(basCvt$,mid$(s$,i,1),1) -1
next i
end function</langsyntaxhighlight>
<table border=1>
<tr bgcolor=wheat align=center><td>Decimal</td><td>To Base</td><td>Num</td><td>to Dec</td></tr>
Line 2,851 ⟶ 3,468:
and hexadecimal base).
 
<langsyntaxhighlight Rustlang="rust">fn format_with_radix(mut n: u32, radix: u32) -> String {
assert!(2 <= radix && radix <= 36);
 
Line 2,885 ⟶ 3,502:
println!("{}", u32::from_str_radix("DeadBeef", 16)?);
Ok(())
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">def backToBig(num: String, oldBase: Int): BigInt = BigInt(num, oldBase)
 
def bigToBase(num: BigInt, newBase: Int): String = num.toString(newBase)</langsyntaxhighlight>
 
=={{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}}==
Line 2,902 ⟶ 3,526:
for corresponding purposes.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
Line 2,912 ⟶ 3,536:
writeln(bigInteger("rosetta", 36)); # Convert string to bigInteger
writeln(integer("code", 36)); # Convert string to integer
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,924 ⟶ 3,548:
=={{header|Sidef}}==
Built-in:
<langsyntaxhighlight lang="ruby">say 60272032366.base(36) # convert number to string
say Number("rosetta", 36) # convert string to number</langsyntaxhighlight>
 
User-defined:
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">static to = [@|'0'..'9', @|'a'..'z']
static from = Hash(to.pairs.map{@|_}.flip...)
 
Line 2,948 ⟶ 3,572:
 
say base_from("rosetta", 36) # string to number
say base_to(60272032366, 36) # number to string</langsyntaxhighlight>
 
=={{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 2,981 ⟶ 3,650:
in
map convert o explode
end</langsyntaxhighlight>
 
Example:
Line 2,995 ⟶ 3,664:
=={{header|Swift}}==
Converting integer to string:
<langsyntaxhighlight lang="swift">println(String(26, radix: 16)) // prints "1a"</langsyntaxhighlight>
 
Converting string to integer:
<langsyntaxhighlight 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"</langsyntaxhighlight>
 
=={{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 3,034 ⟶ 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 3,057 ⟶ 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 3,067 ⟶ 3,736:
 
=={{header|VBA}}==
<langsyntaxhighlight 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
Line 3,090 ⟶ 3,759:
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</langsyntaxhighlight>{{out}}<pre>26 decimal in base 16 is: 1a. Conversely, hexadecimal 1a in decimal is: 26 </pre>
 
=={{header|Wolframalpha}}==
Line 3,100 ⟶ 3,769:
{{libheader|Wren-fmt}}
The methods Conv.itoa and Conv.atoi in the above module provide the required functionality.
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Conv
 
System.print(Conv.itoa(26, 16))
System.print(Conv.atoi("1a", 16))</langsyntaxhighlight>
 
{{out}}
Line 3,112 ⟶ 3,781:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated string convention
 
Line 3,142 ⟶ 3,811:
IntOut(0, Str2Num("1a", 16)); CrLf(0);
IntOut(0, Str2Num("deadbeef", 16)); CrLf(0);
]</langsyntaxhighlight>
 
Output:
Line 3,156 ⟶ 3,825:
=={{header|zkl}}==
The toInt(base) and toString(base) methods do this. base is 2..36
<langsyntaxhighlight lang="zkl">(26).toString(16) //--> "1a"
"1a".toInt(16) //-->26</langsyntaxhighlight>
In addition, string format is able to convert to a base:
<langsyntaxhighlight lang="zkl">"%x %,.2B".fmt(26,26) //-->"1a 1|1010"</langsyntaxhighlight>
 
 
3

edits