Non-decimal radices/Convert: Difference between revisions

Content added Content deleted
(→‎{{header|Phix}}: updated for 1.0.2, syntax coloured)
m (syntax highlighting fixup automation)
Line 20: Line 20:
=={{header|11l}}==
=={{header|11l}}==
Converting from string to number:
Converting from string to number:
<lang 11l>print(Int(‘1A’, radix' 16)) // prints the integer 26</lang>
<syntaxhighlight lang="11l">print(Int(‘1A’, radix' 16)) // prints the integer 26</syntaxhighlight>


Converting from number to string:
Converting from number to string:
<lang 11l>print(String(26, radix' 16)) // prints ‘1A’</lang>
<syntaxhighlight lang="11l">print(String(26, radix' 16)) // prints ‘1A’</syntaxhighlight>


=={{header|8086 Assembly}}==
=={{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.
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.


<lang asm>mov ah,02h
<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.
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.</lang>
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 result is that <code>AX</code> now equals <code>0x0010</code>.
Line 36: Line 36:
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.
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.


<lang asm>mov ax,10h
<syntaxhighlight lang="asm">mov ax,10h
aam
aam
byte 0D5h,10h ;inlined bytecode for AAD using base 16</lang>
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.)
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}}==
=={{header|ACL2}}==
<lang Lisp>(defun digit-value (chr)
<syntaxhighlight lang="lisp">(defun digit-value (chr)
(cond ((and (char>= chr #\0)
(cond ((and (char>= chr #\0)
(char<= chr #\9))
(char<= chr #\9))
Line 77: Line 77:


(defun show-num (num base)
(defun show-num (num base)
(coerce (reverse (num-to-cs num base)) 'string))</lang>
(coerce (reverse (num-to-cs num base)) 'string))</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>CHAR ARRAY digits="0123456789abcdefghijklmnopqrstuvwxyz"
<syntaxhighlight lang="action!">CHAR ARRAY digits="0123456789abcdefghijklmnopqrstuvwxyz"


PROC CheckBase(BYTE b)
PROC CheckBase(BYTE b)
Line 148: Line 148:
PrintF("%U -> base %B %S -> %U%E",v,b,s,v2)
PrintF("%U -> base %B %S -> %U%E",v,b,s,v2)
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Non-decimal_radices_convert.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Non-decimal_radices_convert.png Screenshot from Atari 8-bit computer]
Line 178: Line 178:
=={{header|Ada}}==
=={{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.
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.
<lang ada>with Ada.Text_Io; use Ada.Text_Io;
<syntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
with Ada.Strings.Fixed;
with Ada.Strings.Fixed;
With Ada.Strings.Unbounded;
With Ada.Strings.Unbounded;
Line 231: Line 231:
Put_Line("26 converted to base 16 is " & To_Base(26, 16));
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)));
Put_line("1a (base 16) is decimal" & Integer'image(To_Decimal("1a", 16)));
end Number_Base_Conversion;</lang>
end Number_Base_Conversion;</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>o_text(bfxa(0, 0, 16, 1000000));
<syntaxhighlight lang="aime">o_text(bfxa(0, 0, 16, 1000000));
o_byte('\n');
o_byte('\n');
o_text(bfxa(0, 0, 5, 1000000));
o_text(bfxa(0, 0, 5, 1000000));
Line 246: Line 246:
o_byte('\n');
o_byte('\n');
o_integer(alpha("11110100001001000000", 2));
o_integer(alpha("11110100001001000000", 2));
o_byte('\n');</lang>
o_byte('\n');</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 258: Line 258:
a numbers base.
a numbers base.


<lang algol68>INT base = 16, from dec = 26;
<syntaxhighlight lang="algol68">INT base = 16, from dec = 26;
BITS to bits;
BITS to bits;


Line 271: Line 271:
reset(f);
reset(f);
getf(f, (hex repr, to bits));
getf(f, (hex repr, to bits));
print(("Int: ",ABS to bits, new line))</lang>
print(("Int: ",ABS to bits, new line))</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 288: Line 288:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{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}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<lang algol68>STRING numeric alpha = "0123456789abcdefghijklmnopqrstuvwxyz";
<syntaxhighlight lang="algol68">STRING numeric alpha = "0123456789abcdefghijklmnopqrstuvwxyz";


PROC raise value error = ([]STRING args)VOID: (
PROC raise value error = ([]STRING args)VOID: (
Line 323: Line 323:
INT i = int(s,16); # returns the integer 26 #
INT i = int(s,16); # returns the integer 26 #
print((k," => ", s, " => ", i, new line))
print((k," => ", s, " => ", i, new line))
OD</lang>
OD</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 340: Line 340:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% returns with numberInBase set to the number n converted to a string in %
% 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 %
% the specified base. Number must be non-negative and base must be in %
Line 405: Line 405:
write( 35, i, baseNumber, " ", convertFromBase( baseNumber, i ) );
write( 35, i, baseNumber, " ", convertFromBase( baseNumber, i ) );
end
end
end.</lang>
end.</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
{{Trans|JavaScript}}
{{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:
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:
<lang AppleScript>-- toBase :: Int -> Int -> String
<syntaxhighlight lang="applescript">-- toBase :: Int -> Int -> String
on toBase(intBase, n)
on toBase(intBase, n)
if (intBase < 36) and (intBase > 0) then
if (intBase < 36) and (intBase > 0) then
Line 505: Line 505:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>
{{Out}}
{{Out}}
<lang AppleScript>{{{binary:"11111111", octal:"377", hex:"ff"}, {upperHex:"FF", dgDecimal:"२५५"}},
<syntaxhighlight lang="applescript">{{{binary:"11111111", octal:"377", hex:"ff"}, {upperHex:"FF", dgDecimal:"२५५"}},
{{binary:"11110000", octal:"360", hex:"f0"}, {upperHex:"F0", dgDecimal:"२४०"}}}</lang>
{{binary:"11110000", octal:"360", hex:"f0"}, {upperHex:"F0", dgDecimal:"२४०"}}}</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>fromBase: function [x,base][
<syntaxhighlight lang="rebol">fromBase: function [x,base][
if base=2 [ return from.binary x ]
if base=2 [ return from.binary x ]
if base=8 [ return from.octal x ]
if base=8 [ return from.octal x ]
Line 537: Line 537:
print ["101 => from base2:" fromBase "101" 2 "from base8:" fromBase "101" 8 "from base16:" fromBase "101" 16]
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 ["123 => from base8:" fromBase "123" 8 "from base16:" fromBase "123" 16]
print ["456 => from base8:" fromBase "456" 8 "from base16:" fromBase "456" 16]</lang>
print ["456 => from base8:" fromBase "456" 8 "from base16:" fromBase "456" 16]</syntaxhighlight>


{{out}}
{{out}}
Line 567: Line 567:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>MsgBox % number2base(200, 16) ; 12
<syntaxhighlight lang="autohotkey">MsgBox % number2base(200, 16) ; 12
MsgBox % parse(200, 16) ; 512
MsgBox % parse(200, 16) ; 512


Line 591: Line 591:
}
}
Return result
Return result
}</lang>
}</syntaxhighlight>
alternate implementation contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276241.html#276241 forum]
alternate implementation contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276241.html#276241 forum]
<lang AutoHotkey>MsgBox % ToBase(29,3)
<syntaxhighlight lang="autohotkey">MsgBox % ToBase(29,3)
MsgBox % ToBase(255,16)
MsgBox % ToBase(255,16)


Line 605: Line 605:
FromBase(s,b) { ; convert base b number s=strings of 0..9,a..z, to AHK number
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)
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)
}</lang>
}</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<lang awk>function strtol(str, base)
<syntaxhighlight lang="awk">function strtol(str, base)
{
{
symbols = "0123456789abcdefghijklmnopqrstuvwxyz"
symbols = "0123456789abcdefghijklmnopqrstuvwxyz"
Line 635: Line 635:
print strtol("7b", 16)
print strtol("7b", 16)
print ltostr(123, 16)
print ltostr(123, 16)
}</lang>
}</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> PRINT " 0 (decimal) -> " FNtobase(0, 16) " (base 16)"
<syntaxhighlight lang="bbcbasic"> PRINT " 0 (decimal) -> " FNtobase(0, 16) " (base 16)"
PRINT " 26 (decimal) -> " FNtobase(26, 16) " (base 16)"
PRINT " 26 (decimal) -> " FNtobase(26, 16) " (base 16)"
PRINT "383 (decimal) -> " FNtobase(383, 16) " (base 16)"
PRINT "383 (decimal) -> " FNtobase(383, 16) " (base 16)"
Line 665: Line 665:
A$ = MID$(A$,2)
A$ = MID$(A$,2)
UNTIL A$ = ""
UNTIL A$ = ""
= N%</lang>
= N%</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 680: Line 680:


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang bcpl>get "libhdr";
<syntaxhighlight lang="bcpl">get "libhdr";


// Reverse a string
// Reverse a string
Line 733: Line 733:
for base=10 to 36 do
for base=10 to 36 do
writef("Base %I2: %N*N", base, atoi("25", base))
writef("Base %I2: %N*N", base, atoi("25", base))
$)</lang>
$)</syntaxhighlight>
{{out}}
{{out}}
<pre style='height:50ex;'>1234 in bases 2-36:
<pre style='height:50ex;'>1234 in bases 2-36:
Line 802: Line 802:


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat> ( display
<syntaxhighlight lang="bracmat"> ( display
=
=
. !arg:<10
. !arg:<10
Line 824: Line 824:
& get$:~/#>1:~>36:?b
& get$:~/#>1:~>36:?b
& out$(!n " in base " !b " is " str$(base$(!n.!b)))
& out$(!n " in base " !b " is " str$(base$(!n.!b)))
);</lang>
);</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdlib.h>
<syntaxhighlight lang="c">#include <stdlib.h>
#include <string.h>
#include <string.h>
#include <stdio.h>
#include <stdio.h>
Line 874: Line 874:
printf("%lld in base 16: %s\n", x, to_base(x, 16));
printf("%lld in base 16: %s\n", x, to_base(x, 16));
return 0;
return 0;
}</lang>output
}</syntaxhighlight>output
<pre>-9223372036854775808 in base 2: -1000000000000000000000000000000000000000000000000000000000000000
<pre>-9223372036854775808 in base 2: -1000000000000000000000000000000000000000000000000000000000000000
383 in base 16: 17f</pre>
383 in base 16: 17f</pre>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">
<lang CSharp>
public static class BaseConverter {
public static class BaseConverter {


Line 1,008: Line 1,008:


}
}
</syntaxhighlight>
</lang>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <string>
<syntaxhighlight lang="cpp">#include <string>
#include <cstdlib>
#include <cstdlib>
#include <algorithm>
#include <algorithm>
Line 1,039: Line 1,039:
result = result * base + digits.find(num_str[pos]);
result = result * base + digits.find(num_str[pos]);
return result;
return result;
}</lang>
}</syntaxhighlight>


=={{header|Caché ObjectScript}}==
=={{header|Caché ObjectScript}}==


<lang cos>Class Utils.Number [ Abstract ]
<syntaxhighlight lang="cos">Class Utils.Number [ Abstract ]
{
{


Line 1,109: Line 1,109:
}
}


}</lang>
}</syntaxhighlight>
{{out|Examples}}
{{out|Examples}}
<pre>
<pre>
Line 1,131: Line 1,131:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(parse-integer "1a" :radix 16) ; returns multiple values: 26, 2
<syntaxhighlight lang="lisp">(parse-integer "1a" :radix 16) ; returns multiple values: 26, 2
(write-to-string 26 :base 16) ; also "1A"</lang>
(write-to-string 26 :base 16) ; also "1A"</syntaxhighlight>


Alternative implementation using FORMAT's ~R directive and #nR reader macro
Alternative implementation using FORMAT's ~R directive and #nR reader macro
<lang lisp>(defun decimal-to-base-n (number &key (base 16))
<syntaxhighlight lang="lisp">(defun decimal-to-base-n (number &key (base 16))
(format nil (format nil "~~~dr" base) number))
(format nil (format nil "~~~dr" base) number))


(defun base-n-to-decimal (number &key (base 16))
(defun base-n-to-decimal (number &key (base 16))
(read-from-string (format nil "#~dr~d" base number)))</lang>
(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)
Yet another approach uses FORMAT's ~R in conjunction with ~V for passing arguments to directives (this assumes input as string)
<lang lisp>(defun change-base (number input-base output-base)
<syntaxhighlight lang="lisp">(defun change-base (number input-base output-base)
(format nil "~vr" output-base (parse-integer number :radix input-base)))</lang>
(format nil "~vr" output-base (parse-integer number :radix input-base)))</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
===Using Standard Functions===
===Using Standard Functions===
<lang d>import std.stdio, std.conv, std.string, std.ascii;
<syntaxhighlight lang="d">import std.stdio, std.conv, std.string, std.ascii;


void main() {
void main() {
Line 1,154: Line 1,154:
writeln(60_272_032_366.to!string(36, LetterCase.lower), ' ',
writeln(60_272_032_366.to!string(36, LetterCase.lower), ' ',
591_458.to!string(36, LetterCase.lower));
591_458.to!string(36, LetterCase.lower));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>109517
<pre>109517
Line 1,160: Line 1,160:


===One Implementation===
===One Implementation===
<lang d>import std.stdio, std.array, std.ascii;
<syntaxhighlight lang="d">import std.stdio, std.array, std.ascii;


immutable string mDigits = digits ~ lowercase;
immutable string mDigits = digits ~ lowercase;
Line 1,221: Line 1,221:
writeln(itoaRadix(60_272_032_366, 36), " ",
writeln(itoaRadix(60_272_032_366, 36), " ",
itoaRadix(591_458, 36));
itoaRadix(591_458, 36));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>'1ABcdxyz???' (base 16) = 109517 Converted only: '1ABcd'
<pre>'1ABcdxyz???' (base 16) = 109517 Converted only: '1ABcd'
Line 1,228: Line 1,228:
===Alternative Implementation===
===Alternative Implementation===
{{trans|Haskell}}
{{trans|Haskell}}
<lang d>import std.stdio, std.algorithm, std.ascii, std.array, std.string;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.ascii, std.array, std.string;


alias Digits = ubyte[];
alias Digits = ubyte[];
Line 1,257: Line 1,257:
void main() {
void main() {
"1ABcd".toDigits.fromBase(16).writeln;
"1ABcd".toDigits.fromBase(16).writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
109517
109517


=={{header|E}}==
=={{header|E}}==
<lang e>def stringToInteger := __makeInt
<syntaxhighlight lang="e">def stringToInteger := __makeInt
def integerToString(i :int, base :int) {
def integerToString(i :int, base :int) {
return i.toString(base)
return i.toString(base)
}</lang>
}</syntaxhighlight>


<lang e>? stringToInteger("200", 16)
<syntaxhighlight lang="e">? stringToInteger("200", 16)
# value: 512
# value: 512


? integerToString(200, 16)
? integerToString(200, 16)
# value: "c8"</lang>
# value: "c8"</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>iex(1)> String.to_integer("ffff", 16)
<syntaxhighlight lang="elixir">iex(1)> String.to_integer("ffff", 16)
65535
65535
iex(2)> Integer.to_string(255, 2)
iex(2)> Integer.to_string(255, 2)
"11111111"
"11111111"
iex(3)> String.to_integer("NonDecimalRadices", 36)
iex(3)> String.to_integer("NonDecimalRadices", 36)
188498506820338115928429652</lang>
188498506820338115928429652</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
Line 1,292: Line 1,292:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>function to_base(integer i, integer base)
<syntaxhighlight lang="euphoria">function to_base(integer i, integer base)
integer rem
integer rem
sequence s
sequence s
Line 1,326: Line 1,326:
end for
end for
return i
return i
end function</lang>
end function</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USE: math.parser
<syntaxhighlight lang="factor">USE: math.parser


12345 16 >base .
12345 16 >base .
"3039" 16 base> .</lang>
"3039" 16 base> .</syntaxhighlight>


=={{header|Forth}}==
=={{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.
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.
<lang forth>42 dup
<syntaxhighlight lang="forth">42 dup
2 base !
2 base !
. \ 101010
. \ 101010
hex
hex
. \ 2A
. \ 2A
decimal</lang>
decimal</syntaxhighlight>


Many variants of Forth support literals in some bases, such as hex, using a prefix
Many variants of Forth support literals in some bases, such as hex, using a prefix
<lang forth>$ff . \ 255</lang>
<syntaxhighlight lang="forth">$ff . \ 255</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{Works with|Fortran|90 and later}}
{{Works with|Fortran|90 and later}}
<lang fortran>MODULE Conversion
<syntaxhighlight lang="fortran">MODULE Conversion
IMPLICIT NONE
IMPLICIT NONE
CHARACTER(36) :: alphanum = "0123456789abcdefghijklmnopqrstuvwxyz"
CHARACTER(36) :: alphanum = "0123456789abcdefghijklmnopqrstuvwxyz"
Line 1,393: Line 1,393:
WRITE (*,*) ToBase(16, 26)
WRITE (*,*) ToBase(16, 26)


END PROGRAM</lang>
END PROGRAM</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Function min(x As Integer, y As Integer) As Integer
Function min(x As Integer, y As Integer) As Integer
Line 1,451: Line 1,451:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 1,494: Line 1,494:
=={{header|FunL}}==
=={{header|FunL}}==
Converting from integer to string:
Converting from integer to string:
<lang funl>$stdout = int( '1a', 16 )</lang>
<syntaxhighlight lang="funl">$stdout = int( '1a', 16 )</syntaxhighlight>


{{out}}
{{out}}
Line 1,503: Line 1,503:


Converting from string to integer:
Converting from string to integer:
<lang funl>$stdout = str( 26, 16 )</lang>
<syntaxhighlight lang="funl">$stdout = str( 26, 16 )</syntaxhighlight>


{{out}}
{{out}}
Line 1,518: Line 1,518:
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
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>).
(binary <code>%b</code>, octal <code>%o</code>, decimal <code>%d</code>, and hexidecimal <code>%x</code> or <code>%X</code>).
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,538: Line 1,538:
fmt.Println(b)
fmt.Println(b)
}
}
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<lang groovy>def radixParse = { s, radix -> Integer.parseInt(s, radix) }
<syntaxhighlight lang="groovy">def radixParse = { s, radix -> Integer.parseInt(s, radix) }
def radixFormat = { i, radix -> Integer.toString(i, radix) }</lang>
def radixFormat = { i, radix -> Integer.toString(i, radix) }</syntaxhighlight>


Test Program:
Test Program:
<lang groovy>def numString = '101'
<syntaxhighlight lang="groovy">def numString = '101'
(2..Character.MAX_RADIX).each { radix ->
(2..Character.MAX_RADIX).each { radix ->
def value = radixParse(numString, radix)
def value = radixParse(numString, radix)
Line 1,556: Line 1,556:
assert valM2str == biggestDigit + biggestDigit
assert valM2str == biggestDigit + biggestDigit
printf ("%3s (%2d) - 2 (10) == %4s (%2d)\n", numString, radix, valM2str, radix)
printf ("%3s (%2d) - 2 (10) == %4s (%2d)\n", numString, radix, valM2str, radix)
}</lang>
}</syntaxhighlight>


Output:
Output:
Line 1,634: Line 1,634:
Using built-in functions to convert integer into string, and vice versa, at any base up to 16:
Using built-in functions to convert integer into string, and vice versa, at any base up to 16:


<lang haskell>Prelude> Numeric.showIntAtBase 16 Char.intToDigit 42 ""
<syntaxhighlight lang="haskell">Prelude> Numeric.showIntAtBase 16 Char.intToDigit 42 ""
"2a"
"2a"
Prelude> fst $ head $ Numeric.readInt 16 Char.isHexDigit Char.digitToInt "2a"
Prelude> fst $ head $ Numeric.readInt 16 Char.isHexDigit Char.digitToInt "2a"
42</lang>
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.
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,643: Line 1,643:
So conversion to and from digits represented as 0-9 and a-z is done in an additional step.
So conversion to and from digits represented as 0-9 and a-z is done in an additional step.


<lang haskell>import Data.List
<syntaxhighlight lang="haskell">import Data.List
import Data.Char
import Data.Char


Line 1,663: Line 1,663:
convert c | isDigit c = ord c - ord '0'
convert c | isDigit c = ord c - ord '0'
| isUpper c = ord c - ord 'A' + 10
| isUpper c = ord c - ord 'A' + 10
| isLower c = ord c - ord 'a' + 10</lang>
| isLower c = ord c - ord 'a' + 10</syntaxhighlight>


Example:
Example:


<lang haskell>*Main> toAlphaDigits $ toBase 16 $ 42
<syntaxhighlight lang="haskell">*Main> toAlphaDigits $ toBase 16 $ 42
"2a"
"2a"
*Main> fromBase 16 $ fromAlphaDigits $ "2a"
*Main> fromBase 16 $ fromAlphaDigits $ "2a"
42</lang>
42</syntaxhighlight>




Line 1,677: Line 1,677:
If we want to assume a default character set, then a general '''toBase''' (Int -> Int -> String) can be also be derived from '''inBaseDigits'''.
If we want to assume a default character set, then a general '''toBase''' (Int -> Int -> String) can be also be derived from '''inBaseDigits'''.


<lang haskell>import Data.Bifunctor (first)
<syntaxhighlight lang="haskell">import Data.Bifunctor (first)
import Data.List (unfoldr)
import Data.List (unfoldr)
import Data.Tuple (swap)
import Data.Tuple (swap)
Line 1,730: Line 1,730:
, inHinduArabicDecimal
, inHinduArabicDecimal
] <*>
] <*>
[254]</lang>
[254]</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,743: Line 1,743:


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang hicest>CHARACTER txt*80
<syntaxhighlight lang="hicest">CHARACTER txt*80


num = 36^7 -1 ! 7836416410
num = 36^7 -1 ! 7836416410
Line 1,770: Line 1,770:
temp = INT(temp / base)
temp = INT(temp / base)
ENDDO
ENDDO
END</lang>
END</syntaxhighlight>
<lang hicest>num=7836416410; txt=zzzzzzz; 7836416410;</lang>
<syntaxhighlight lang="hicest">num=7836416410; txt=zzzzzzz; 7836416410;</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{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.
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.


<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
every ( ns := "16r5a" | "-12r1a" ) &
every ( ns := "16r5a" | "-12r1a" ) &
( b := 8 | 12 | 16 ) do {
( b := 8 | 12 | 16 ) do {
Line 1,801: Line 1,801:
return p || reverse(s)
return p || reverse(s)
}
}
end</lang>
end</syntaxhighlight>


{{libheader|Icon Programming Library}}
{{libheader|Icon Programming Library}}
Line 1,816: Line 1,816:
=={{header|J}}==
=={{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:
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:
<lang j> 2b100 8b100 10b_100 16b100 36b100 36bzy
<syntaxhighlight lang="j"> 2b100 8b100 10b_100 16b100 36b100 36bzy
4 64 _100 256 1296 1294</lang>
4 64 _100 256 1296 1294</syntaxhighlight>


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.
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:
Here are programs for conversion of numeric values to literals, and of literals to numbers:
<lang j>numerals=: '0123456789abcdefghijklmnopqrstuvwxyz'
<syntaxhighlight lang="j">numerals=: '0123456789abcdefghijklmnopqrstuvwxyz'
baseNtoL=: numerals {~ #.inv
baseNtoL=: numerals {~ #.inv
baseLtoN=: [ #. numerals i. ]</lang>
baseLtoN=: [ #. numerals i. ]</syntaxhighlight>
Examples of use:
Examples of use:
<lang j> 2 baseNtoL 100 101
<syntaxhighlight lang="j"> 2 baseNtoL 100 101
1100100
1100100
1100101
1100101
Line 1,832: Line 1,832:
1a
1a
36 baseLtoN 'zy'
36 baseLtoN 'zy'
1294</lang>
1294</syntaxhighlight>
These may be combined so the conversion performed is derived from the type of argument received.
These may be combined so the conversion performed is derived from the type of argument received.
<lang j> base=: baseNtoL :: baseLtoN
<syntaxhighlight lang="j"> base=: baseNtoL :: baseLtoN
16 base 'aa'
16 base 'aa'
170
170
16 base 170
16 base 170
aa</lang>
aa</syntaxhighlight>
See also primary verbs [http://www.jsoftware.com/help/dictionary/d401.htm Base] and [http://www.jsoftware.com/help/dictionary/d402.htm Antibase].
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}}==
=={{header|Java}}==
for long's:
for long's:
<lang java>public static long backToTen(String num, int oldBase){
<syntaxhighlight lang="java">public static long backToTen(String num, int oldBase){
return Long.parseLong(num, oldBase); //takes both uppercase and lowercase letters
return Long.parseLong(num, oldBase); //takes both uppercase and lowercase letters
}
}
Line 1,850: Line 1,850:
public static String tenToBase(long num, int newBase){
public static String tenToBase(long num, int newBase){
return Long.toString(num, newBase);//add .toUpperCase() for capital letters
return Long.toString(num, newBase);//add .toUpperCase() for capital letters
}</lang>
}</syntaxhighlight>


for BigInteger's:
for BigInteger's:
<lang java>public static BigInteger backToTenBig(String num, int oldBase){
<syntaxhighlight lang="java">public static BigInteger backToTenBig(String num, int oldBase){
return new BigInteger(num, oldBase); //takes both uppercase and lowercase letters
return new BigInteger(num, oldBase); //takes both uppercase and lowercase letters
}
}
Line 1,859: Line 1,859:
public static String tenBigToBase(BigInteger num, int newBase){
public static String tenBigToBase(BigInteger num, int newBase){
return num.toString(newBase);//add .toUpperCase() for capital letters
return num.toString(newBase);//add .toUpperCase() for capital letters
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
===ES5===
===ES5===
<lang javascript>k = 26
<syntaxhighlight lang="javascript">k = 26
s = k.toString(16) //gives 1a
s = k.toString(16) //gives 1a
i = parseInt('1a',16) //gives 26
i = parseInt('1a',16) //gives 26
//optional special case for hex:
//optional special case for hex:
i = +('0x'+s) //hexadecimal base 16, if s='1a' then i=26.</lang>
i = +('0x'+s) //hexadecimal base 16, if s='1a' then i=26.</syntaxhighlight>


Converts a number of arbitrary length from any base to any base
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!!
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.
Debugging or following the process is easy as it is kept in the expected base string format and order.
<lang javascript>
<syntaxhighlight lang="javascript">
var baselist = "0123456789abcdefghijklmnopqrstuvwxyz", listbase = [];
var baselist = "0123456789abcdefghijklmnopqrstuvwxyz", listbase = [];
for(var i = 0; i < baselist.length; i++) listbase[baselist[i]] = i; // Generate baselist reverse
for(var i = 0; i < baselist.length; i++) listbase[baselist[i]] = i; // Generate baselist reverse
Line 1,891: Line 1,891:
return to.join('');
return to.join('');
}
}
console.log("Result:", basechange("zzzzzzzzzz", 36, 10));</lang>
console.log("Result:", basechange("zzzzzzzzzz", 36, 10));</syntaxhighlight>
Using BigInteger, can convert any base.
Using BigInteger, can convert any base.
<lang javascript>
<syntaxhighlight lang="javascript">
// Tom Wu jsbn.js http://www-cs-students.stanford.edu/~tjw/jsbn/
// Tom Wu jsbn.js http://www-cs-students.stanford.edu/~tjw/jsbn/
var baselist = "0123456789abcdefghijklmnopqrstuvwxyz", listbase = [];
var baselist = "0123456789abcdefghijklmnopqrstuvwxyz", listbase = [];
Line 1,922: Line 1,922:
return to.join('');
return to.join('');
}
}
</syntaxhighlight>
</lang>


===ES6===
===ES6===
Line 1,928: Line 1,928:
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.
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.


<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 2,020: Line 2,020:
devanagariDecimal: inDevanagariDecimal(n)
devanagariDecimal: inDevanagariDecimal(n)
}));
}));
})();</lang>
})();</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,040: Line 2,040:


=={{header|jq}}==
=={{header|jq}}==
<lang jq># Convert the input integer to a string in the specified base (2 to 36 inclusive)
<syntaxhighlight lang="jq"># Convert the input integer to a string in the specified base (2 to 36 inclusive)
def convert(base):
def convert(base):
def stream:
def stream:
Line 2,061: Line 2,061:
# state: [power, ans]
# state: [power, ans]
([1,0]; (.[0] * base) as $b | [$b, .[1] + (.[0] * $c)])
([1,0]; (.[0] * base) as $b | [$b, .[1] + (.[0] * $c)])
| .[1];</lang>
| .[1];</syntaxhighlight>
'''Example''':
'''Example''':
<lang jq>(255 | convert(16)),
<syntaxhighlight lang="jq">(255 | convert(16)),
("ff" | to_i(16)),
("ff" | to_i(16)),
("10" | to_i(10))</lang>
("10" | to_i(10))</syntaxhighlight>
{{Out}}
{{Out}}
$jq -M -r -n -f Non-decimal_radices.jq
$jq -M -r -n -f Non-decimal_radices.jq
Line 2,073: Line 2,073:


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>
<syntaxhighlight lang="julia">
@show string(185, base=2)
@show string(185, base=2)
@show string(185, base=3)
@show string(185, base=3)
Line 2,089: Line 2,089:
@show string(185, base=15)
@show string(185, base=15)
@show string(185, base=16)
@show string(185, base=16)
</lang>{{out}}
</syntaxhighlight>{{out}}
<pre>
<pre>
string(185, base = 2) = "10111001"
string(185, base = 2) = "10111001"
Line 2,111: Line 2,111:
An approach from first principles rather than using Java library functions:
An approach from first principles rather than using Java library functions:
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun min(x: Int, y: Int) = if (x < y) x else y
fun min(x: Int, y: Int) = if (x < y) x else y
Line 2,155: Line 2,155:
println("36 base $f = ${s.padEnd(6)} -> base $f = ${convertToDecimal(s, b)}")
println("36 base $f = ${s.padEnd(6)} -> base $f = ${convertToDecimal(s, b)}")
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,199: Line 2,199:


Converting decimal numbers 26 and 3000 in LFE, using some different mechanisms:
Converting decimal numbers 26 and 3000 in LFE, using some different mechanisms:
<lang lisp>
<syntaxhighlight lang="lisp">
> (: erlang list_to_integer '"1a" 16)
> (: erlang list_to_integer '"1a" 16)
26
26
Line 2,212: Line 2,212:
> (: erlang integer_to_list 3000 2)
> (: erlang integer_to_list 3000 2)
"101110111000"
"101110111000"
</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb> ' Base Converter v6
<syntaxhighlight lang="lb"> ' Base Converter v6


global alphanum$
global alphanum$
Line 2,247: Line 2,247:
next i
next i
end function
end function
</lang>
</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
Only had to write 'dec2base' as the reverse is provided by the in-built function 'tonumber'
Only had to write 'dec2base' as the reverse is provided by the in-built function 'tonumber'
<lang Lua>function dec2base (base, n)
<syntaxhighlight lang="lua">function dec2base (base, n)
local result, digit = ""
local result, digit = ""
while n > 0 do
while n > 0 do
Line 2,264: Line 2,264:
local x = dec2base(16, 26)
local x = dec2base(16, 26)
print(x) --> 1a
print(x) --> 1a
print(tonumber(x, 16)) --> 26</lang>
print(tonumber(x, 16)) --> 26</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Module Checkit {
k$=lambda$ (m, b as integer=16) -> {
k$=lambda$ (m, b as integer=16) -> {
Line 2,294: Line 2,294:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 2,308: Line 2,308:


=={{header|M4}}==
=={{header|M4}}==
<lang M4>eval(26,16)
<syntaxhighlight lang="m4">eval(26,16)
define(`frombase',`eval(0r$2:$1)')
define(`frombase',`eval(0r$2:$1)')
frombase(1a,16)</lang>
frombase(1a,16)</syntaxhighlight>


Output:
Output:
Line 2,320: Line 2,320:


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>#converts a number to a given based represented by a string
<syntaxhighlight lang="maple">#converts a number to a given based represented by a string
to_base := proc(num, based)
to_base := proc(num, based)
local i;
local i;
Line 2,350: Line 2,350:
end do;
end do;
return result;
return result;
end proc:</lang>
end proc:</syntaxhighlight>
{{Out|Usage}}
{{Out|Usage}}
<pre>
<pre>
Line 2,368: Line 2,368:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Use the built-in functions IntegerString[] and FromDigits[]:
Use the built-in functions IntegerString[] and FromDigits[]:
<lang Mathematica>IntegerString[26,16]
<syntaxhighlight lang="mathematica">IntegerString[26,16]
FromDigits["1a", 16])</lang>
FromDigits["1a", 16])</syntaxhighlight>
{{out}}
{{out}}
<pre>"1a"
<pre>"1a"
Line 2,376: Line 2,376:
=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
Use the built-in functions base2dec() and dec2base():
Use the built-in functions base2dec() and dec2base():
<lang Matlab>dec2base(26,16)
<syntaxhighlight lang="matlab">dec2base(26,16)
base2dec('1a', 16)</lang>
base2dec('1a', 16)</syntaxhighlight>


Output:
Output:
Line 2,402: Line 2,402:
=={{header|NetRexx}}==
=={{header|NetRexx}}==
In NetRexx numbers are held as Rexx strings so you can take advantage of Java's BigInteger to do radix conversions.
In NetRexx numbers are held as Rexx strings so you can take advantage of Java's BigInteger to do radix conversions.
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 2,441: Line 2,441:
bi = BigInteger(val.toString(), 10)
bi = BigInteger(val.toString(), 10)
return bi.toString(radix)
return bi.toString(radix)
</syntaxhighlight>
</lang>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 2,467: Line 2,467:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import strutils
<syntaxhighlight lang="nim">import strutils


proc reverse(a: string): string =
proc reverse(a: string): string =
Line 2,499: Line 2,499:


echo 26.toBase 16
echo 26.toBase 16
echo "1a".fromBase 16</lang>
echo "1a".fromBase 16</syntaxhighlight>
Output:
Output:
<pre>1a
<pre>1a
Line 2,505: Line 2,505:


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let int_of_basen n str =
<syntaxhighlight lang="ocaml">let int_of_basen n str =
match n with
match n with
| 16 -> int_of_string("0x" ^ str)
| 16 -> int_of_string("0x" ^ str)
Line 2,516: Line 2,516:
| 16 -> Printf.sprintf "%x" d
| 16 -> Printf.sprintf "%x" d
| 8 -> Printf.sprintf "%o" d
| 8 -> Printf.sprintf "%o" d
| _ -> failwith "unhandled"</lang>
| _ -> failwith "unhandled"</syntaxhighlight>


# basen_of_int 16 26 ;;
# basen_of_int 16 26 ;;
Line 2,526: Line 2,526:
A real base conversion example: {{trans|Haskell}}
A real base conversion example: {{trans|Haskell}}


<lang ocaml>let to_base b v =
<syntaxhighlight lang="ocaml">let to_base b v =
let rec to_base' a v =
let rec to_base' a v =
if v = 0 then
if v = 0 then
Line 2,557: Line 2,557:
let result = ref [] in
let result = ref [] in
String.iter (fun c -> result := from_alpha_digit c :: !result) s;
String.iter (fun c -> result := from_alpha_digit c :: !result) s;
List.rev !result</lang>
List.rev !result</syntaxhighlight>


Example:
Example:
Line 2,569: Line 2,569:


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>toBase(n,b)={
<syntaxhighlight lang="parigp">toBase(n,b)={
my(s="",t);
my(s="",t);
while(n,
while(n,
Line 2,585: Line 2,585:
);
);
t
t
};</lang>
};</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
{{libheader| Math SysUtils}}
{{libheader| Math SysUtils}}
{{works with|Free_Pascal}}
{{works with|Free_Pascal}}
<lang pascal>Program ConvertDemo(output);
<syntaxhighlight lang="pascal">Program ConvertDemo(output);


uses
uses
Line 2,635: Line 2,635:
writeln ('26: ', ToBase(16, 26));
writeln ('26: ', ToBase(16, 26));
end.
end.
</syntaxhighlight>
</lang>
Output:
Output:
<pre>% ./Convert
<pre>% ./Convert
Line 2,643: Line 2,643:
=={{header|Perl}}==
=={{header|Perl}}==
For base 2 and 16, we can do this entirely with language features:
For base 2 and 16, we can do this entirely with language features:
<lang perl>sub to2 { sprintf "%b", shift; }
<syntaxhighlight lang="perl">sub to2 { sprintf "%b", shift; }
sub to16 { sprintf "%x", shift; }
sub to16 { sprintf "%x", shift; }
sub from2 { unpack("N", pack("B32", substr("0" x 32 . shift, -32))); }
sub from2 { unpack("N", pack("B32", substr("0" x 32 . shift, -32))); }
sub from16 { hex(shift); }</lang>
sub from16 { hex(shift); }</syntaxhighlight>


Small functions will handle arbitrary base conversions for bases 2-36:
Small functions will handle arbitrary base conversions for bases 2-36:
<lang perl>sub base_to {
<syntaxhighlight lang="perl">sub base_to {
my($n,$b) = @_;
my($n,$b) = @_;
my $s = "";
my $s = "";
Line 2,665: Line 2,665:
}
}
$t;
$t;
}</lang>
}</syntaxhighlight>


There are a plethora of modules that perform base conversion.
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.
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.
<lang perl>use POSIX;
<syntaxhighlight lang="perl">use POSIX;
my ($num, $n_unparsed) = strtol('1a', 16);
my ($num, $n_unparsed) = strtol('1a', 16);
$n_unparsed == 0 or die "invalid characters found";
$n_unparsed == 0 or die "invalid characters found";
print "$num\n"; # prints "26"</lang>
print "$num\n"; # prints "26"</syntaxhighlight>


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}}
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}}
<lang perl>use ntheory qw/fromdigits todigitstring/;
<syntaxhighlight lang="perl">use ntheory qw/fromdigits todigitstring/;
my $n = 65261;
my $n = 65261;
my $n16 = todigitstring($n, 16) || 0;
my $n16 = todigitstring($n, 16) || 0;
my $n10 = fromdigits($n16, 16);
my $n10 = fromdigits($n16, 16);
say "$n $n16 $n10"; # prints "65261 feed 65261"</lang>
say "$n $n16 $n10"; # prints "65261 feed 65261"</syntaxhighlight>


Other modules include but are not limited to:
Other modules include but are not limited to:
Line 2,703: Line 2,703:
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_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>
mpz_get_str(), mpfr_get_str() [desktop/Phix only], and mpfr_get_fixed() can generate output strings in all bases 2..62.<br>
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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: #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>
Line 2,713: Line 2,713:
<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;">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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
The following (given the above not necessarily very useful) routines can handle simple integer conversions, in bases 2 to 36.<br>
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.
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.
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Convert_base.exw</span>
<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: #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>
Line 2,740: Line 2,740:
<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;">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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,749: Line 2,749:
=={{header|PHP}}==
=={{header|PHP}}==
PHP has a base_convert() function that directly converts between strings of one base and strings of another base:
PHP has a base_convert() function that directly converts between strings of one base and strings of another base:
<lang php>base_convert("26", 10, 16); // returns "1a"</lang>
<syntaxhighlight lang="php">base_convert("26", 10, 16); // returns "1a"</syntaxhighlight>


If you want to convert a string to an integer, the intval() function optionally takes a base argument when given a string:
If you want to convert a string to an integer, the intval() function optionally takes a base argument when given a string:
<lang php>intval("1a", 16); // returns 26</lang>
<syntaxhighlight lang="php">intval("1a", 16); // returns 26</syntaxhighlight>


To go the other way around, I guess you can use base_convert() again; I am unaware of a better way:
To go the other way around, I guess you can use base_convert() again; I am unaware of a better way:
<lang php>base_convert(26, 10, 16); // returns "1a"</lang>
<syntaxhighlight lang="php">base_convert(26, 10, 16); // returns "1a"</syntaxhighlight>


In addition, there are specialized functions for converting certain bases:
In addition, there are specialized functions for converting certain bases:
<lang php>// converts int to binary string
<syntaxhighlight lang="php">// converts int to binary string
decbin(26); // returns "11010"
decbin(26); // returns "11010"
// converts int to octal string
// converts int to octal string
Line 2,769: Line 2,769:
octdec("32"); // returns 26
octdec("32"); // returns 26
// converts hex string to int
// converts hex string to int
hexdec("1a"); // returns 26</lang>
hexdec("1a"); // returns 26</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de numToString (N Base)
<syntaxhighlight lang="picolisp">(de numToString (N Base)
(default Base 10)
(default Base 10)
(let L NIL
(let L NIL
Line 2,793: Line 2,793:
(prinl (numToString 26 16))
(prinl (numToString 26 16))
(prinl (stringToNum "1a" 16))
(prinl (stringToNum "1a" 16))
(prinl (numToString 123456789012345678901234567890 36))</lang>
(prinl (numToString 123456789012345678901234567890 36))</syntaxhighlight>
Output:
Output:
<pre>"1a"
<pre>"1a"
Line 2,800: Line 2,800:


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
convert: procedure (N, base) returns (character (64) varying) recursive;
convert: procedure (N, base) returns (character (64) varying) recursive;
declare N fixed binary (31), base fixed binary;
declare N fixed binary (31), base fixed binary;
Line 2,813: Line 2,813:
return (s || table(mod(N, base)) );
return (s || table(mod(N, base)) );
end convert;
end convert;
</syntaxhighlight>
</lang>


=={{header|PL/M}}==
=={{header|PL/M}}==
<lang pli>100H:
<syntaxhighlight lang="pli">100H:


/* CONVERT A NUMBER TO A GIVEN BASE */
/* CONVERT A NUMBER TO A GIVEN BASE */
Line 2,893: Line 2,893:


CALL EXIT;
CALL EXIT;
EOF</lang>
EOF</syntaxhighlight>
{{out}}
{{out}}
<pre style='height:50ex;'>1234 IN BASES 2-36:
<pre style='height:50ex;'>1234 IN BASES 2-36:
Line 2,969: Line 2,969:
built-in procedures:
built-in procedures:


<lang pop11>define number_to_base(n, base);
<syntaxhighlight lang="pop11">define number_to_base(n, base);
radix_apply(n, '%p', sprintf, base);
radix_apply(n, '%p', sprintf, base);
enddefine;</lang>
enddefine;</syntaxhighlight>


In input base optionally preceeds the number, for example
In input base optionally preceeds the number, for example
Line 2,977: Line 2,977:
to prepend base prefix and read number from string:
to prepend base prefix and read number from string:


<lang pop11>define string_in_base_to_number(s, base);
<syntaxhighlight lang="pop11">define string_in_base_to_number(s, base);
incharitem(stringin(base >< ':' >< s))();
incharitem(stringin(base >< ':' >< s))();
enddefine;</lang>
enddefine;</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Global alphanum$ = "0123456789abcdefghijklmnopqrstuvwxyz" ;36 digits
<syntaxhighlight lang="purebasic">Global alphanum$ = "0123456789abcdefghijklmnopqrstuvwxyz" ;36 digits
#maxIntegerBitSize = SizeOf(Integer) * 8
#maxIntegerBitSize = SizeOf(Integer) * 8
Line 3,017: Line 3,017:
Input()
Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>
Sample output:
Sample output:
<pre>26
<pre>26
Line 3,025: Line 3,025:
===Python: string to number===
===Python: string to number===
Converting from string to number is straight forward:
Converting from string to number is straight forward:
<lang python>i = int('1a',16) # returns the integer 26</lang>
<syntaxhighlight lang="python">i = int('1a',16) # returns the integer 26</syntaxhighlight>


===Python: number to string===
===Python: number to string===
Line 3,031: Line 3,031:
;Recursive:
;Recursive:


<lang python>digits = "0123456789abcdefghijklmnopqrstuvwxyz"
<syntaxhighlight lang="python">digits = "0123456789abcdefghijklmnopqrstuvwxyz"
def baseN(num, b):
def baseN(num, b):
return digits[num] if num < b else baseN(num // b, b) + digits[num % b]</lang>
return digits[num] if num < b else baseN(num // b, b) + digits[num % b]</syntaxhighlight>


;Iterative:
;Iterative:


<lang python>digits = "0123456789abcdefghijklmnopqrstuvwxyz"
<syntaxhighlight lang="python">digits = "0123456789abcdefghijklmnopqrstuvwxyz"


def baseN(num, b):
def baseN(num, b):
Line 3,045: Line 3,045:
result.append(digits[d])
result.append(digits[d])
result.append(digits[num])
result.append(digits[num])
return ''.join(result[::-1])</lang>
return ''.join(result[::-1])</syntaxhighlight>


;Sample run from either:
;Sample run from either:
Line 3,056: Line 3,056:
The built-in word <code>number$</code> (included in listing) provides conversion of a number to a string in the current <code>base</code>. The valid range of bases is 2 to 36 inclusive, digits greater than 9 are represented by upper-case letters. The word <code>>base$</code> adapts <code>number$</code>to the requirements of the task by temporarily overriding the current <code>base</code> and converting the returned string from upper to lower case.
The built-in word <code>number$</code> (included in listing) provides conversion of a number to a string in the current <code>base</code>. The valid range of bases is 2 to 36 inclusive, digits greater than 9 are represented by upper-case letters. The word <code>>base$</code> adapts <code>number$</code>to the requirements of the task by temporarily overriding the current <code>base</code> and converting the returned string from upper to lower case.


<lang Quackery>( [ $ '' over abs
<syntaxhighlight lang="quackery">( [ $ '' over abs
[ base share /mod digit
[ base share /mod digit
rot join swap
rot join swap
Line 3,073: Line 3,073:
say "The number 2970609818455516403037 in hexatrigesimal is "
say "The number 2970609818455516403037 in hexatrigesimal is "
2970609818455516403037 36 >base$ echo$
2970609818455516403037 36 >base$ echo$
say "."</lang>
say "."</syntaxhighlight>


{{out}}
{{out}}
Line 3,082: Line 3,082:


=={{header|R}}==
=={{header|R}}==
<syntaxhighlight lang="r">
<lang R>




Line 3,112: Line 3,112:
str2int("1a", 16)
str2int("1a", 16)


</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==


<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket


Line 3,138: Line 3,138:
(printf "~s -> ~a#~a -> ~a => ~a\n" N S r M (if (= M N) 'OK 'BAD)))
(printf "~s -> ~a#~a -> ~a => ~a\n" N S r M (if (= M N) 'OK 'BAD)))
;; (random-test)
;; (random-test)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>sub from-base(Str $str, Int $base) {
<syntaxhighlight lang="raku" line>sub from-base(Str $str, Int $base) {
+":$base\<$str>";
+":$base\<$str>";
}
}
Line 3,148: Line 3,148:
sub to-base(Real $num, Int $base) {
sub to-base(Real $num, Int $base) {
$num.base($base);
$num.base($base);
}</lang>
}</syntaxhighlight>
These work on any real type including integer types.
These work on any real type including integer types.


Line 3,171: Line 3,171:
└─┐ of 10 to be used. The limits of bases are: 2 ──► 90. ┌─┘
└─┐ of 10 to be used. The limits of bases are: 2 ──► 90. ┌─┘
└────────────────────────────────────────────────────────────────────┘
└────────────────────────────────────────────────────────────────────┘
<lang rexx>/*REXX program converts integers from one base to another (using bases 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*/
@abc = 'abcdefghijklmnopqrstuvwxyz' /*lowercase (Latin or English) alphabet*/
parse upper var @abc @abcU /*uppercase a version of @abc. */
parse upper var @abc @abcU /*uppercase a version of @abc. */
Line 3,207: Line 3,207:
erd: call ser 'illegal digit/numeral ['?"] in: " x
erd: call ser 'illegal digit/numeral ['?"] in: " x
erm: call ser 'no argument specified.'
erm: call ser 'no argument specified.'
ser: say; say '***error!***'; say arg(1); exit 13</lang>
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>}}
{{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>
<pre>
Line 3,226: Line 3,226:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Non-decimal radices/Convert
# Project : Non-decimal radices/Convert


Line 3,256: Line 3,256:
next
next
return binsum
return binsum
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 3,272: Line 3,272:
=={{header|Ruby}}==
=={{header|Ruby}}==
This converts strings from any base to any base up to base 36.
This converts strings from any base to any base up to base 36.
<lang ruby>class String
<syntaxhighlight lang="ruby">class String
def convert_base(from, to)
def convert_base(from, to)
Integer(self, from).to_s(to)
Integer(self, from).to_s(to)
Line 3,284: Line 3,284:
p "50664".convert_base(7, 10) # =>"12345"
p "50664".convert_base(7, 10) # =>"12345"
p "1038334289300125869792154778345043071467300".convert_base(10, 36) # =>"zombieseatingdeadvegetables"
p "1038334289300125869792154778345043071467300".convert_base(10, 36) # =>"zombieseatingdeadvegetables"
p "ff".convert_base(15, 10) # => ArgumentError</lang>
p "ff".convert_base(15, 10) # => ArgumentError</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>global basCvt$
<syntaxhighlight lang="runbasic">global basCvt$
basCvt$ ="0123456789abcdefghijklmnopqrstuvwxyz"
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>"
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 3,314: Line 3,314:
toDecimal = toDecimal * b + instr(basCvt$,mid$(s$,i,1),1) -1
toDecimal = toDecimal * b + instr(basCvt$,mid$(s$,i,1),1) -1
next i
next i
end function</lang>
end function</syntaxhighlight>
<table border=1>
<table border=1>
<tr bgcolor=wheat align=center><td>Decimal</td><td>To Base</td><td>Num</td><td>to Dec</td></tr>
<tr bgcolor=wheat align=center><td>Decimal</td><td>To Base</td><td>Num</td><td>to Dec</td></tr>
Line 3,333: Line 3,333:
and hexadecimal base).
and hexadecimal base).


<lang Rust>fn format_with_radix(mut n: u32, radix: u32) -> String {
<syntaxhighlight lang="rust">fn format_with_radix(mut n: u32, radix: u32) -> String {
assert!(2 <= radix && radix <= 36);
assert!(2 <= radix && radix <= 36);


Line 3,367: Line 3,367:
println!("{}", u32::from_str_radix("DeadBeef", 16)?);
println!("{}", u32::from_str_radix("DeadBeef", 16)?);
Ok(())
Ok(())
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang Scala>def backToBig(num: String, oldBase: Int): BigInt = BigInt(num, oldBase)
<syntaxhighlight lang="scala">def backToBig(num: String, oldBase: Int): BigInt = BigInt(num, oldBase)


def bigToBase(num: BigInt, newBase: Int): String = num.toString(newBase)</lang>
def bigToBase(num: BigInt, newBase: Int): String = num.toString(newBase)</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
Line 3,384: Line 3,384:
for corresponding purposes.
for corresponding purposes.


<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
include "bigint.s7i";
Line 3,394: Line 3,394:
writeln(bigInteger("rosetta", 36)); # Convert string to bigInteger
writeln(bigInteger("rosetta", 36)); # Convert string to bigInteger
writeln(integer("code", 36)); # Convert string to integer
writeln(integer("code", 36)); # Convert string to integer
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 3,406: Line 3,406:
=={{header|Sidef}}==
=={{header|Sidef}}==
Built-in:
Built-in:
<lang ruby>say 60272032366.base(36) # convert number to string
<syntaxhighlight lang="ruby">say 60272032366.base(36) # convert number to string
say Number("rosetta", 36) # convert string to number</lang>
say Number("rosetta", 36) # convert string to number</syntaxhighlight>


User-defined:
User-defined:
{{trans|Perl}}
{{trans|Perl}}
<lang ruby>static to = [@|'0'..'9', @|'a'..'z']
<syntaxhighlight lang="ruby">static to = [@|'0'..'9', @|'a'..'z']
static from = Hash(to.pairs.map{@|_}.flip...)
static from = Hash(to.pairs.map{@|_}.flip...)


Line 3,430: Line 3,430:


say base_from("rosetta", 36) # string to number
say base_from("rosetta", 36) # string to number
say base_to(60272032366, 36) # number to string</lang>
say base_to(60272032366, 36) # number to string</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>26 printString &radix: 16
<syntaxhighlight lang="slate">26 printString &radix: 16
Integer readFrom: '1A' &radix: 16.</lang>
Integer readFrom: '1A' &radix: 16.</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>26 printStringRadix:16 -> '1A'
<syntaxhighlight lang="smalltalk">26 printStringRadix:16 -> '1A'
Integer readFrom:'1A' radix:16 -> 26
Integer readFrom:'1A' radix:16 -> 26


Line 3,443: Line 3,443:
'radix %2d: %s\n' printf:{radix . 100 printStringRadix:radix } on:Transcript.
'radix %2d: %s\n' printf:{radix . 100 printStringRadix:radix } on:Transcript.
].
].
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>radix 2: 1100100
<pre>radix 2: 1100100
Line 3,484: Line 3,484:
{{trans|Haskell}}
{{trans|Haskell}}


<lang sml>fun toBase b v = let
<syntaxhighlight lang="sml">fun toBase b v = let
fun toBase' (a, 0) = a
fun toBase' (a, 0) = a
| toBase' (a, v) = toBase' (v mod b :: a, v div b)
| toBase' (a, v) = toBase' (v mod b :: a, v div b)
Line 3,508: Line 3,508:
in
in
map convert o explode
map convert o explode
end</lang>
end</syntaxhighlight>


Example:
Example:
Line 3,522: Line 3,522:
=={{header|Swift}}==
=={{header|Swift}}==
Converting integer to string:
Converting integer to string:
<lang swift>println(String(26, radix: 16)) // prints "1a"</lang>
<syntaxhighlight lang="swift">println(String(26, radix: 16)) // prints "1a"</syntaxhighlight>


Converting string to integer:
Converting string to integer:
<lang swift>import Darwin
<syntaxhighlight lang="swift">import Darwin
func string2int(s: String, radix: Int) -> Int {
func string2int(s: String, radix: Int) -> Int {
return strtol(s, nil, Int32(radix))
return strtol(s, nil, Int32(radix))
// there is also strtoul() for UInt, and strtoll() and strtoull() for Int64 and UInt64, respectively
// there is also strtoul() for UInt, and strtoll() and strtoull() for Int64 and UInt64, respectively
}
}
println(string2int("1a", 16)) // prints "26"</lang>
println(string2int("1a", 16)) // prints "26"</syntaxhighlight>


=={{header|Tcl}}==
=={{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.
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.
<lang tcl>namespace eval baseconvert {
<syntaxhighlight lang="tcl">namespace eval baseconvert {
variable chars "0123456789abcdefghijklmnopqrstuvwxyz"
variable chars "0123456789abcdefghijklmnopqrstuvwxyz"
namespace export baseconvert
namespace export baseconvert
Line 3,561: Line 3,561:
baseconvert 12345 10 23 ;# ==> 107h
baseconvert 12345 10 23 ;# ==> 107h
baseconvert 107h 23 7 ;# ==> 50664
baseconvert 107h 23 7 ;# ==> 50664
baseconvert 50664 7 10 ;# ==> 12345</lang>
baseconvert 50664 7 10 ;# ==> 12345</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
A function parameterized by the base b performs the conversion in each direction.
A function parameterized by the base b performs the conversion in each direction.
Folding (=>), iteration (->), and reification (-:) operators among others are helpful.
Folding (=>), iteration (->), and reification (-:) operators among others are helpful.
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import nat
#import nat


num_to_string "b" = ||'0'! (-: num digits--letters)*+ @NiX ~&r->l ^|rrPlCrlPX/~& division\"b"
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"</lang>
string_to_num "b" = @x =>0 sum^|/(-:@rlXS num digits--letters) product/"b"</syntaxhighlight>
This test program performs the conversions in both directions for a selection of numbers
This test program performs the conversions in both directions for a selection of numbers
in base 8 and base 32.
in base 8 and base 32.
<lang Ursala>test_data = <1,2,15,32,100,65536,323498993>
<syntaxhighlight lang="ursala">test_data = <1,2,15,32,100,65536,323498993>


#cast %sLnLUL
#cast %sLnLUL
Line 3,584: Line 3,584:
string_to_num32* num_to_string32* test_data,
string_to_num32* num_to_string32* test_data,
num_to_string8* test_data,
num_to_string8* test_data,
string_to_num8* num_to_string8* test_data></lang>
string_to_num8* num_to_string8* test_data></syntaxhighlight>
output:
output:
<pre>
<pre>
Line 3,594: Line 3,594:


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Private Function to_base(ByVal number As Long, base As Integer) As String
<syntaxhighlight lang="vb">Private Function to_base(ByVal number As Long, base As Integer) As String
Dim digits As String, result As String
Dim digits As String, result As String
Dim i As Integer, digit As Integer
Dim i As Integer, digit As Integer
Line 3,617: Line 3,617:
Public Sub Non_decimal_radices_Convert()
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)
Debug.Print "26 decimal in base 16 is: "; to_base(26, 16); ". Conversely, hexadecimal 1a in decimal is: "; from_base("1a", 16)
End Sub</lang>{{out}}<pre>26 decimal in base 16 is: 1a. Conversely, hexadecimal 1a in decimal is: 26 </pre>
End Sub</syntaxhighlight>{{out}}<pre>26 decimal in base 16 is: 1a. Conversely, hexadecimal 1a in decimal is: 26 </pre>


=={{header|Wolframalpha}}==
=={{header|Wolframalpha}}==
Line 3,627: Line 3,627:
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
The methods Conv.itoa and Conv.atoi in the above module provide the required functionality.
The methods Conv.itoa and Conv.atoi in the above module provide the required functionality.
<lang ecmascript>import "/fmt" for Conv
<syntaxhighlight lang="ecmascript">import "/fmt" for Conv


System.print(Conv.itoa(26, 16))
System.print(Conv.itoa(26, 16))
System.print(Conv.atoi("1a", 16))</lang>
System.print(Conv.atoi("1a", 16))</syntaxhighlight>


{{out}}
{{out}}
Line 3,639: Line 3,639:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated string convention
string 0; \use zero-terminated string convention


Line 3,669: Line 3,669:
IntOut(0, Str2Num("1a", 16)); CrLf(0);
IntOut(0, Str2Num("1a", 16)); CrLf(0);
IntOut(0, Str2Num("deadbeef", 16)); CrLf(0);
IntOut(0, Str2Num("deadbeef", 16)); CrLf(0);
]</lang>
]</syntaxhighlight>


Output:
Output:
Line 3,683: Line 3,683:
=={{header|zkl}}==
=={{header|zkl}}==
The toInt(base) and toString(base) methods do this. base is 2..36
The toInt(base) and toString(base) methods do this. base is 2..36
<lang zkl>(26).toString(16) //--> "1a"
<syntaxhighlight lang="zkl">(26).toString(16) //--> "1a"
"1a".toInt(16) //-->26</lang>
"1a".toInt(16) //-->26</syntaxhighlight>
In addition, string format is able to convert to a base:
In addition, string format is able to convert to a base:
<lang zkl>"%x %,.2B".fmt(26,26) //-->"1a 1|1010"</lang>
<syntaxhighlight lang="zkl">"%x %,.2B".fmt(26,26) //-->"1a 1|1010"</syntaxhighlight>