Non-decimal radices/Convert: Difference between revisions
no edit summary
Puppydrum64 (talk | contribs) |
No edit summary |
||
(16 intermediate revisions by 10 users not shown) | |||
Line 20:
=={{header|11l}}==
Converting from string to number:
<
Converting from number to string:
<
=={{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.
<
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.</
The result is that <code>AX</code> now equals <code>0x0010</code>.
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.
<
aam
byte 0D5h,10h ;inlined bytecode for AAD using base 16</
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}}==
<
(cond ((and (char>= chr #\0)
(char<= chr #\9))
Line 77:
(defun show-num (num base)
(coerce (reverse (num-to-cs num base)) 'string))</
=={{header|Action!}}==
<
PROC CheckBase(BYTE b)
Line 148:
PrintF("%U -> base %B %S -> %U%E",v,b,s,v2)
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Non-decimal_radices_convert.png Screenshot from Atari 8-bit computer]
Line 178:
=={{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.
<
with Ada.Strings.Fixed;
With Ada.Strings.Unbounded;
Line 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;</
=={{header|Aime}}==
<
o_byte('\n');
o_text(bfxa(0, 0, 5, 1000000));
Line 246:
o_byte('\n');
o_integer(alpha("11110100001001000000", 2));
o_byte('\n');</
=={{header|ALGOL 68}}==
Line 258:
a numbers base.
<
BITS to bits;
Line 271:
reset(f);
getf(f, (hex repr, to bits));
print(("Int: ",ABS to bits, new line))</
Output:
<pre>
Line 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}}
<
PROC raise value error = ([]STRING args)VOID: (
Line 323:
INT i = int(s,16); # returns the integer 26 #
print((k," => ", s, " => ", i, new line))
OD</
Output:
<pre>
Line 340:
=={{header|ALGOL W}}==
<
% 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 405:
write( 35, i, baseNumber, " ", convertFromBase( baseNumber, i ) );
end
end.</
=={{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:
<
on toBase(intBase, n)
if (intBase < 36) and (intBase > 0) then
Line 505:
end script
end if
end mReturn</
{{Out}}
<
{{binary:"11110000", octal:"360", hex:"f0"}, {upperHex:"F0", dgDecimal:"२४०"}}}</
=={{header|Arturo}}==
<
if base=2 [ return from.binary x ]
if base=8 [ return from.octal x ]
Line 537:
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]</
{{out}}
Line 567:
=={{header|AutoHotkey}}==
<
MsgBox % parse(200, 16) ; 512
Line 591:
}
Return result
}</
alternate implementation contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276241.html#276241 forum]
<
MsgBox % ToBase(255,16)
Line 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)
}</
=={{header|AWK}}==
<
{
symbols = "0123456789abcdefghijklmnopqrstuvwxyz"
Line 635:
print strtol("7b", 16)
print ltostr(123, 16)
}</
=={{header|BBC BASIC}}==
<
PRINT " 26 (decimal) -> " FNtobase(26, 16) " (base 16)"
PRINT "383 (decimal) -> " FNtobase(383, 16) " (base 16)"
Line 665:
A$ = MID$(A$,2)
UNTIL A$ = ""
= N%</
'''Output:'''
<pre>
Line 680:
=={{header|BCPL}}==
<
// Reverse a string
Line 733:
for base=10 to 36 do
writef("Base %I2: %N*N", base, atoi("25", base))
$)</
{{out}}
<pre style='height:50ex;'>1234 in bases 2-36:
Line 802:
=={{header|Bracmat}}==
<
=
. !arg:<10
Line 824:
& get$:~/#>1:~>36:?b
& out$(!n " in base " !b " is " str$(base$(!n.!b)))
);</
=={{header|C}}==
<
#include <string.h>
#include <stdio.h>
Line 874:
printf("%lld in base 16: %s\n", x, to_base(x, 16));
return 0;
}</
<pre>-9223372036854775808 in base 2: -1000000000000000000000000000000000000000000000000000000000000000
383 in base 16: 17f</pre>
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">
public static class BaseConverter {
Line 1,008:
}
</syntaxhighlight>
=={{header|C++}}==
<
#include <cstdlib>
#include <algorithm>
Line 1,039:
result = result * base + digits.find(num_str[pos]);
return result;
}</
=={{header|Caché ObjectScript}}==
<
{
Line 1,109:
}
}</
{{out|Examples}}
<pre>
Line 1,131:
=={{header|Common Lisp}}==
<
(write-to-string 26 :base 16) ; also "1A"</
Alternative implementation using FORMAT's ~R directive and #nR reader macro
<
(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)))</
Yet another approach uses FORMAT's ~R in conjunction with ~V for passing arguments to directives (this assumes input as string)
<
(format nil "~vr" output-base (parse-integer number :radix input-base)))</
=={{header|D}}==
===Using Standard Functions===
<
void main() {
Line 1,154:
writeln(60_272_032_366.to!string(36, LetterCase.lower), ' ',
591_458.to!string(36, LetterCase.lower));
}</
{{out}}
<pre>109517
Line 1,160:
===One Implementation===
<
immutable string mDigits = digits ~ lowercase;
Line 1,221:
writeln(itoaRadix(60_272_032_366, 36), " ",
itoaRadix(591_458, 36));
}</
{{out}}
<pre>'1ABcdxyz???' (base 16) = 109517 Converted only: '1ABcd'
Line 1,228:
===Alternative Implementation===
{{trans|Haskell}}
<
alias Digits = ubyte[];
Line 1,257:
void main() {
"1ABcd".toDigits.fromBase(16).writeln;
}</
{{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}}==
<
def integerToString(i :int, base :int) {
return i.toString(base)
}</
<
# value: 512
? integerToString(200, 16)
# value: "c8"</
=={{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}}==
<
65535
iex(2)> Integer.to_string(255, 2)
"11111111"
iex(3)> String.to_integer("NonDecimalRadices", 36)
188498506820338115928429652</
=={{header|Erlang}}==
Line 1,292 ⟶ 1,402:
=={{header|Euphoria}}==
<
integer rem
sequence s
Line 1,326 ⟶ 1,436:
end for
return i
end function</
=={{header|Factor}}==
<
12345 16 >base .
"3039" 16 base> .</
=={{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.
<
2 base !
. \ 101010
hex
. \ 2A
decimal</
Many variants of Forth support literals in some bases, such as hex, using a prefix
<syntaxhighlight lang
=={{header|Fortran}}==
{{Works with|Fortran|90 and later}}
<
IMPLICIT NONE
CHARACTER(36) :: alphanum = "0123456789abcdefghijklmnopqrstuvwxyz"
Line 1,393 ⟶ 1,503:
WRITE (*,*) ToBase(16, 26)
END PROGRAM</
=={{header|FreeBASIC}}==
<
Function min(x As Integer, y As Integer) As Integer
Line 1,451 ⟶ 1,561:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,494 ⟶ 1,604:
=={{header|FunL}}==
Converting from integer to string:
<
{{out}}
Line 1,503 ⟶ 1,613:
Converting from string to integer:
<
{{out}}
Line 1,518 ⟶ 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>).
<
import (
Line 1,538 ⟶ 1,648:
fmt.Println(b)
}
}</
=={{header|Groovy}}==
Solution:
<
def radixFormat = { i, radix -> Integer.toString(i, radix) }</
Test Program:
<
(2..Character.MAX_RADIX).each { radix ->
def value = radixParse(numString, radix)
Line 1,556 ⟶ 1,666:
assert valM2str == biggestDigit + biggestDigit
printf ("%3s (%2d) - 2 (10) == %4s (%2d)\n", numString, radix, valM2str, radix)
}</
Output:
Line 1,634 ⟶ 1,744:
Using built-in functions to convert integer into string, and vice versa, at any base up to 16:
<
"2a"
Prelude> fst $ head $ Numeric.readInt 16 Char.isHexDigit Char.digitToInt "2a"
42</
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 ⟶ 1,753:
So conversion to and from digits represented as 0-9 and a-z is done in an additional step.
<
import Data.Char
Line 1,663 ⟶ 1,773:
convert c | isDigit c = ord c - ord '0'
| isUpper c = ord c - ord 'A' + 10
| isLower c = ord c - ord 'a' + 10</
Example:
<
"2a"
*Main> fromBase 16 $ fromAlphaDigits $ "2a"
42</
Line 1,677 ⟶ 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'''.
<
import Data.List (unfoldr)
import Data.Tuple (swap)
Line 1,730 ⟶ 1,840:
, inHinduArabicDecimal
] <*>
[254]</
{{Out}}
Line 1,743 ⟶ 1,853:
=={{header|HicEst}}==
<
num = 36^7 -1 ! 7836416410
Line 1,770 ⟶ 1,880:
temp = INT(temp / base)
ENDDO
END</
<
=={{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.
<
every ( ns := "16r5a" | "-12r1a" ) &
( b := 8 | 12 | 16 ) do {
Line 1,801 ⟶ 1,911:
return p || reverse(s)
}
end</
{{libheader|Icon Programming Library}}
Line 1,816 ⟶ 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:
<
4 64 _100 256 1296 1294</
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:
<
baseNtoL=: numerals {~ #.inv
baseLtoN=: [ #. numerals i. ]</
Examples of use:
<
1100100
1100101
Line 1,832 ⟶ 1,942:
1a
36 baseLtoN 'zy'
1294</
These may be combined so the conversion performed is derived from the type of argument received.
<
16 base 'aa'
170
16 base 170
aa</
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:
<
return Long.parseLong(num, oldBase); //takes both uppercase and lowercase letters
}
Line 1,850 ⟶ 1,960:
public static String tenToBase(long num, int newBase){
return Long.toString(num, newBase);//add .toUpperCase() for capital letters
}</
for BigInteger's:
<
return new BigInteger(num, oldBase); //takes both uppercase and lowercase letters
}
Line 1,859 ⟶ 1,969:
public static String tenBigToBase(BigInteger num, int newBase){
return num.toString(newBase);//add .toUpperCase() for capital letters
}</
=={{header|JavaScript}}==
===ES5===
<
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.</
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.
<
var baselist = "0123456789abcdefghijklmnopqrstuvwxyz", listbase = [];
for(var i = 0; i < baselist.length; i++) listbase[baselist[i]] = i; // Generate baselist reverse
Line 1,891 ⟶ 2,001:
return to.join('');
}
console.log("Result:", basechange("zzzzzzzzzz", 36, 10));</
Using BigInteger, can convert any base.
<
// Tom Wu jsbn.js http://www-cs-students.stanford.edu/~tjw/jsbn/
var baselist = "0123456789abcdefghijklmnopqrstuvwxyz", listbase = [];
Line 1,922 ⟶ 2,032:
return to.join('');
}
</syntaxhighlight>
===ES6===
Line 1,928 ⟶ 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.
<
'use strict';
Line 2,020 ⟶ 2,130:
devanagariDecimal: inDevanagariDecimal(n)
}));
})();</
{{Out}}
Line 2,038 ⟶ 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}}==
<
def convert(base):
def stream:
recurse(if . >=
[stream] | reverse
| if base < 10 then map(tostring) | join("")
elif base <= 36 then map(if . < 10 then 48 + . else . + 87 end) | implode
else error("base too large")
end;
# input string is converted from "base" to an integer, within limits
Line 2,061 ⟶ 2,184:
# state: [power, ans]
([1,0]; (.[0] * base) as $b | [$b, .[1] + (.[0] * $c)])
| .[1];</
'''Example''':
<
("ff" | to_i(16)),
("10" | to_i(10))</
{{Out}}
$jq -M -r -n -f Non-decimal_radices.jq
Line 2,073 ⟶ 2,196:
=={{header|Julia}}==
<
@show string(185, base=2)
@show string(185, base=3)
Line 2,089 ⟶ 2,212:
@show string(185, base=15)
@show string(185, base=16)
</
<pre>
string(185, base = 2) = "10111001"
Line 2,111 ⟶ 2,234:
An approach from first principles rather than using Java library functions:
{{trans|FreeBASIC}}
<
fun min(x: Int, y: Int) = if (x < y) x else y
Line 2,155 ⟶ 2,278:
println("36 base $f = ${s.padEnd(6)} -> base $f = ${convertToDecimal(s, b)}")
}
}</
{{out}}
Line 2,199 ⟶ 2,322:
Converting decimal numbers 26 and 3000 in LFE, using some different mechanisms:
<
> (: erlang list_to_integer '"1a" 16)
26
Line 2,212 ⟶ 2,335:
> (: erlang integer_to_list 3000 2)
"101110111000"
</syntaxhighlight>
=={{header|Liberty BASIC}}==
<
global alphanum$
Line 2,247 ⟶ 2,370:
next i
end function
</
=={{header|Lua}}==
Only had to write 'dec2base' as the reverse is provided by the in-built function 'tonumber'
<
local result
local digit = n % base
if digit > 9 then
end
result = digit .. result
n = n // base
until n == 0
return result
end
Line 2,264 ⟶ 2,389:
local x = dec2base(16, 26)
print(x) --> 1a
print(tonumber(x, 16)) --> 26</
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
k$=lambda$ (m, b as integer=16) -> {
Line 2,294 ⟶ 2,419:
}
Checkit
</syntaxhighlight>
Output:
<pre>
Line 2,308 ⟶ 2,433:
=={{header|M4}}==
<
define(`frombase',`eval(0r$2:$1)')
frombase(1a,16)</
Output:
Line 2,320 ⟶ 2,445:
=={{header|Maple}}==
<
to_base := proc(num, based)
local i;
Line 2,350 ⟶ 2,475:
end do;
return result;
end proc:</
{{Out|Usage}}
<pre>
Line 2,368 ⟶ 2,493:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Use the built-in functions IntegerString[] and FromDigits[]:
<
FromDigits["1a", 16])</
{{out}}
<pre>"1a"
Line 2,376 ⟶ 2,501:
=={{header|MATLAB}} / {{header|Octave}}==
Use the built-in functions base2dec() and dec2base():
<
base2dec('1a', 16)</
Output:
Line 2,402 ⟶ 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.
<
options replace format comments java crossref symbols nobinary
Line 2,441 ⟶ 2,566:
bi = BigInteger(val.toString(), 10)
return bi.toString(radix)
</syntaxhighlight>
'''Output:'''
<pre>
Line 2,467 ⟶ 2,592:
=={{header|Nim}}==
<
proc reverse(a: string): string =
Line 2,499 ⟶ 2,624:
echo 26.toBase 16
echo "1a".fromBase 16</
Output:
<pre>1a
Line 2,505 ⟶ 2,630:
=={{header|OCaml}}==
<
match n with
| 16 -> int_of_string("0x" ^ str)
Line 2,516 ⟶ 2,641:
| 16 -> Printf.sprintf "%x" d
| 8 -> Printf.sprintf "%o" d
| _ -> failwith "unhandled"</
# basen_of_int 16 26 ;;
Line 2,524 ⟶ 2,649:
- : int = 26
A real base conversion
<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 []))
let
| '0' .. '9' -> int_of_char '0'
| 'a' .. 'z' -> int_of_char 'a' - 10
|
| _ -> invalid_arg "unkown digit"
in
String.fold_left (fun n d -> n * b + of_sym d) 0 ds</syntaxhighlight>
Example:
<pre>
#
- : string = "
#
- : int =
</pre>
=={{header|PARI/GP}}==
<
my(s="",t);
while(n,
Line 2,585 ⟶ 2,694:
);
t
};</
=={{header|Pascal}}==
{{libheader| Math SysUtils}}
{{works with|Free_Pascal}}
<
uses
Line 2,635 ⟶ 2,744:
writeln ('26: ', ToBase(16, 26));
end.
</syntaxhighlight>
Output:
<pre>% ./Convert
Line 2,643 ⟶ 2,752:
=={{header|Perl}}==
For base 2 and 16, we can do this entirely with language features:
<
sub to16 { sprintf "%x", shift; }
sub from2 { unpack("N", pack("B32", substr("0" x 32 . shift, -32))); }
sub from16 { hex(shift); }</
Small functions will handle arbitrary base conversions for bases 2-36:
<
my($n,$b) = @_;
my $s = "";
$s
} while $n = int($n / $b);
}
sub base_from {
Line 2,665 ⟶ 2,773:
}
$t;
}</
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.
<
my ($num, $n_unparsed) = strtol('1a', 16);
$n_unparsed == 0 or die "invalid characters found";
print "$num\n"; # prints "26"</
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}}
<
my $n = 65261;
my $n16 = todigitstring($n, 16) || 0;
my $n10 = fromdigits($n16, 16);
say "$n $n16 $n10"; # prints "65261 feed 65261"</
Other modules include but are not limited to:
Line 2,696 ⟶ 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
The (s)printf() routine can generate strings in decimal, binary, octal, hexadecimal, or
The builtin to_number() function has an inbase parameter which defaults to 10 but can be 2..
Note however that only decimal fractions are supported in the core language itself, and to_number(), and that (s)printf's %d..A are all integer-only, and %e/f/g decimal-only.<br>
Also note that 0t is(/was) an alternative for 0o (octal) on desktop/Phix, but not supported by JavaScript and hence pwa/p2js.<br>
mpz_set_str() and mpfr_set_str() can handle input strings expressed in decimal, binary (0b prefix), hexadecimal (0x prefix), or bases 2..62, including non-decimal fractions.<br>
mpz_get_str(), mpfr_get_str() [desktop/Phix only], and mpfr_get_fixed() can generate output strings in all bases 2..62.<br>
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #0000FF;">?{</span><span style="color: #000000;">26</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0b11010</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0o32</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0x1A</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0X1a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">#1A</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0(16)1A</span><span style="color: #0000FF;">}</span> <span style="color: #000080;font-style:italic;">-- displays {26,26,26,26,26,26,26}</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d == 0b%b == 0x%x\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">26</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays 26 == 0b11010 == 0x1A</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d == o(62)%A\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">26</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">62</span><span style="color: #0000FF;">,</span><span style="color: #000000;">26</span><span style="color: #0000FF;">}})</span> <span style="color: #000080;font-style:italic;">-- displays 26 == 0(62)Q</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">to_number</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1a"</span><span style="color: #0000FF;">,{},</span><span style="color: #000000;">16</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays 26</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">mpfr</span> <span style="color: #000000;">f</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpfr_init</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">mpfr_set_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"110.01"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"0b%s == %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">mpfr_get_fixed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">mpfr_get_fixed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">)})</span> <span style="color: #000080;font-style:italic;">-- 0b110.01 == 6.25</span>
<!--</syntaxhighlight>-->
The following (given the above not necessarily very useful) routines can handle simple integer conversions, in bases 2 to 36.<br>
You are expected to strip any leading "#" or "0x" from hexadecimal input strings (etc) manually, and (as-is) only use a-z not A-Z.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Convert_base.exw</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">to_base</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prepend</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">+</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;"><</span><span style="color: #000000;">10</span><span style="color: #0000FF;">?</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">:</span><span style="color: #008000;">'a'</span><span style="color: #0000FF;">-</span><span style="color: #000000;">10</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">/</span><span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"0"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">from_base</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">*</span><span style="color: #000000;">base</span><span style="color: #0000FF;">+(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">-</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;"><=</span><span style="color: #008000;">'9'</span><span style="color: #0000FF;">?</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">:</span><span style="color: #008000;">'a'</span><span style="color: #0000FF;">-</span><span style="color: #000000;">10</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">to_base</span><span style="color: #0000FF;">(</span><span style="color: #000000;">256</span><span style="color: #0000FF;">,</span><span style="color: #000000;">16</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">from_base</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"100"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">16</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,752 ⟶ 2,857:
=={{header|PHP}}==
PHP has a base_convert() function that directly converts between strings of one base and strings of another base:
<
If you want to convert a string to an integer, the intval() function optionally takes a base argument when given a string:
<
To go the other way around, I guess you can use base_convert() again; I am unaware of a better way:
<
In addition, there are specialized functions for converting certain bases:
<
decbin(26); // returns "11010"
// converts int to octal string
Line 2,772 ⟶ 2,877:
octdec("32"); // returns 26
// converts hex string to int
hexdec("1a"); // returns 26</
=={{header|PicoLisp}}==
<
(default Base 10)
(let L NIL
Line 2,796 ⟶ 2,901:
(prinl (numToString 26 16))
(prinl (stringToNum "1a" 16))
(prinl (numToString 123456789012345678901234567890 36))</
Output:
<pre>"1a"
Line 2,803 ⟶ 2,908:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
convert: procedure (N, base) returns (character (64) varying) recursive;
declare N fixed binary (31), base fixed binary;
Line 2,816 ⟶ 2,921:
return (s || table(mod(N, base)) );
end convert;
</syntaxhighlight>
=={{header|PL/M}}==
<
/* CONVERT A NUMBER TO A GIVEN BASE */
Line 2,896 ⟶ 3,001:
CALL EXIT;
EOF</
{{out}}
<pre style='height:50ex;'>1234 IN BASES 2-36:
Line 2,972 ⟶ 3,077:
built-in procedures:
<
radix_apply(n, '%p', sprintf, base);
enddefine;</
In input base optionally preceeds the number, for example
Line 2,980 ⟶ 3,085:
to prepend base prefix and read number from string:
<
incharitem(stringin(base >< ':' >< s))();
enddefine;</
=={{header|PureBasic}}==
<
#maxIntegerBitSize = SizeOf(Integer) * 8
Line 3,020 ⟶ 3,125:
Input()
CloseConsole()
EndIf</
Sample output:
<pre>26
Line 3,028 ⟶ 3,133:
===Python: string to number===
Converting from string to number is straight forward:
<
===Python: number to string===
Line 3,034 ⟶ 3,139:
;Recursive:
<
def baseN(num, b):
return digits[num] if num < b else baseN(num // b, b) + digits[num % b]</
;Iterative:
<
def baseN(num, b):
Line 3,048 ⟶ 3,153:
result.append(digits[d])
result.append(digits[num])
return ''.join(result[::-1])</
;Sample run from either:
Line 3,057 ⟶ 3,162:
=={{header|Quackery}}==
Handles radices in the range 2 to 36.
<
number$
base release
$
witheach
[ lower join ] ]
[ 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">
Line 3,115 ⟶ 3,222:
str2int("1a", 16)
</syntaxhighlight>
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
Line 3,141 ⟶ 3,248:
(printf "~s -> ~a#~a -> ~a => ~a\n" N S r M (if (= M N) 'OK 'BAD)))
;; (random-test)
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
+":$base\<$str>";
}
Line 3,151 ⟶ 3,258:
sub to-base(Real $num, Int $base) {
$num.base($base);
}</
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 3,174 ⟶ 3,281:
└─┐ of 10 to be used. The limits of bases are: 2 ──► 90. ┌─┘
└────────────────────────────────────────────────────────────────────┘
<
@abc = 'abcdefghijklmnopqrstuvwxyz' /*lowercase (Latin or English) alphabet*/
parse upper var @abc @abcU /*uppercase a version of @abc. */
Line 3,210 ⟶ 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</
{{out|output|text= when input is expressed in hexadecimal (maximum positive integer in a signed 32-bit word): <tt> 7fffffff , 16 </tt>}}
<pre>
Line 3,229 ⟶ 3,336:
=={{header|Ring}}==
<
# Project : Non-decimal radices/Convert
Line 3,259 ⟶ 3,366:
next
return binsum
</syntaxhighlight>
Output:
<pre>
Line 3,271 ⟶ 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.
<
def convert_base(from, to)
Integer(self, from).to_s(to)
Line 3,287 ⟶ 3,419:
p "50664".convert_base(7, 10) # =>"12345"
p "1038334289300125869792154778345043071467300".convert_base(10, 36) # =>"zombieseatingdeadvegetables"
p "ff".convert_base(15, 10) # => ArgumentError</
=={{header|Run BASIC}}==
<
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 3,317 ⟶ 3,449:
toDecimal = toDecimal * b + instr(basCvt$,mid$(s$,i,1),1) -1
next i
end function</
<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,336 ⟶ 3,468:
and hexadecimal base).
<
assert!(2 <= radix && radix <= 36);
Line 3,370 ⟶ 3,502:
println!("{}", u32::from_str_radix("DeadBeef", 16)?);
Ok(())
}</
=={{header|Scala}}==
<
def bigToBase(num: BigInt, newBase: Int): String = num.toString(newBase)</syntaxhighlight>
=={{header|Scheme}}==
R7RS specifies only a radix of 2, 8, 10, or 16 for the functions below. However, some implementations support arbitrary (e.g. Chibi-Scheme or Guile).
<syntaxhighlight lang="scheme">
(number->string 26 16)
(string->number "1a" 16)</syntaxhighlight>
=={{header|Seed7}}==
Line 3,387 ⟶ 3,526:
for corresponding purposes.
<
include "bigint.s7i";
Line 3,397 ⟶ 3,536:
writeln(bigInteger("rosetta", 36)); # Convert string to bigInteger
writeln(integer("code", 36)); # Convert string to integer
end func;</
{{out}}
Line 3,409 ⟶ 3,548:
=={{header|Sidef}}==
Built-in:
<
say Number("rosetta", 36) # convert string to number</
User-defined:
{{trans|Perl}}
<
static from = Hash(to.pairs.map{@|_}.flip...)
Line 3,433 ⟶ 3,572:
say base_from("rosetta", 36) # string to number
say base_to(60272032366, 36) # number to string</
=={{header|Slate}}==
<
Integer readFrom: '1A' &radix: 16.</
=={{header|Smalltalk}}==
<
Integer readFrom:'1A' radix:16 -> 26
Line 3,446 ⟶ 3,585:
'radix %2d: %s\n' printf:{radix . 100 printStringRadix:radix } on:Transcript.
].
</syntaxhighlight>
{{out}}
<pre>radix 2: 1100100
Line 3,487 ⟶ 3,626:
{{trans|Haskell}}
<
fun toBase' (a, 0) = a
| toBase' (a, v) = toBase' (v mod b :: a, v div b)
Line 3,511 ⟶ 3,650:
in
map convert o explode
end</
Example:
Line 3,525 ⟶ 3,664:
=={{header|Swift}}==
Converting integer to string:
<
Converting string to integer:
<
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"</
=={{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.
<
variable chars "0123456789abcdefghijklmnopqrstuvwxyz"
namespace export baseconvert
Line 3,564 ⟶ 3,703:
baseconvert 12345 10 23 ;# ==> 107h
baseconvert 107h 23 7 ;# ==> 50664
baseconvert 50664 7 10 ;# ==> 12345</
=={{header|Ursala}}==
A function parameterized by the base b performs the conversion in each direction.
Folding (=>), iteration (->), and reification (-:) operators among others are helpful.
<
#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"</
This test program performs the conversions in both directions for a selection of numbers
in base 8 and base 32.
<
#cast %sLnLUL
Line 3,587 ⟶ 3,726:
string_to_num32* num_to_string32* test_data,
num_to_string8* test_data,
string_to_num8* num_to_string8* test_data></
output:
<pre>
Line 3,597 ⟶ 3,736:
=={{header|VBA}}==
<
Dim digits As String, result As String
Dim i As Integer, digit As Integer
Line 3,620 ⟶ 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</
=={{header|Wolframalpha}}==
Line 3,630 ⟶ 3,769:
{{libheader|Wren-fmt}}
The methods Conv.itoa and Conv.atoi in the above module provide the required functionality.
<
System.print(Conv.itoa(26, 16))
System.print(Conv.atoi("1a", 16))</
{{out}}
Line 3,642 ⟶ 3,781:
=={{header|XPL0}}==
<
string 0; \use zero-terminated string convention
Line 3,672 ⟶ 3,811:
IntOut(0, Str2Num("1a", 16)); CrLf(0);
IntOut(0, Str2Num("deadbeef", 16)); CrLf(0);
]</
Output:
Line 3,686 ⟶ 3,825:
=={{header|zkl}}==
The toInt(base) and toString(base) methods do this. base is 2..36
<
"1a".toInt(16) //-->26</
In addition, string format is able to convert to a base:
<
|