Non-decimal radices/Output: Difference between revisions
m
syntax highlighting fixup automation
(→{{header|Phix}}: added syntax colouring, marked p2js compatible, also fixing the <lang phix> lowercase p error.) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 15:
=={{header|11l}}==
<
print(bin(n)‘ ’String(n, radix' 8)‘ ’n‘ ’hex(n))</
{{out}}
Line 25:
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<
PROC Main()
Line 41:
LMARGIN=old ;restore left margin on the screen
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Non-decimal_radices_output.png Screenshot from Atari 8-bit computer]
Line 58:
=={{header|Ada}}==
<
with Ada.Text_IO; use Ada.Text_IO;
Line 69:
New_Line;
end loop;
end Test_Integer_Text_IO;</
Sample output:
<pre style="height:30ex;overflow:scroll">
Line 108:
=={{header|Aime}}==
<
o_byte('\n');
o_xinteger(5, 1000000);
o_byte('\n');
o_xinteger(2, 1000000);
o_byte('\n');</
=={{header|ALGOL 68}}==
Line 122:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - printf has been removed}}
<
FOR i TO 33 DO
printf(($10r6d," "16r6d," "8r6dl$, BIN i, BIN i, BIN i))
OD
)</
Sample output:
<pre>
Line 166:
=={{header|ALGOL W}}==
Algol W has a standard procedure intbase16 that returns its parameter converted to a string in hexadecimal.
<
% print some numbers in hex %
for i := 0 until 20 do write( intbase16( i ) )
end.</
{{out}}
<pre>
Line 197:
=={{header|AutoHotkey}}==
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276235.html#276235 forum]
<
BC(NumStr,InputBase=8,OutputBase=10) {
Line 203:
DllCall("msvcrt\_i64toa","Int64",DllCall("msvcrt\_strtoui64","Str",NumStr,"Uint",0,"UInt",InputBase,"CDECLInt64"),"Str",S,"UInt",OutputBase,"CDECL")
Return S
}</
=={{header|Arturo}}==
<
print [
pad as.binary i 6
Line 213:
pad to :string i 2
pad as.hex i 2
]</
{{out}}
Line 254:
=={{header|AWK}}==
C's printf() is just exposed:
<
10
10 012 0xa
Line 260:
16 020 0x10
255
255 0377 0xff</
=={{header|BBC BASIC}}==
<
PRINT STR$(0)
PRINT STR$(123456789)
Line 270:
REM STR$~ converts to a hexadecimal string:
PRINT STR$~(43981)
PRINT STR$~(-1)</
'''Output:'''
<pre>
Line 283:
Variable <code>obase</code> is the base for all output. It can be 2 (binary) up to some implementation-dependent limit. In [[GNU bc]] the limit may be large, for example 2^31, with "digits" of bases bigger than 36 printed as individual decimal numbers.
{{works with|GNU bc}}
<syntaxhighlight lang="bc">
for(i=1;i<10;i++) {
obase=10; print i," "
Line 290:
obase=2; print i
print "\n"
}</
{{out}}
<pre>1 1 1 1
Line 304:
=={{header|C}}==
<
int main()
Line 314:
return 0;
}</
Binary conversion using <tt>%b</tt> is not standard.
=={{header|C sharp}}==
<
using System;
Line 340:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 391:
=={{header|C++}}==
<
#include <iomanip>
Line 402:
return 0;
}</
=={{header|Clojure}}==
Clojure eschews duplicating functionality already present in Java when interop is sufficiently idiomatic:
<
(Integer/toOctalString 25) ; returns "31"
(Integer/toHexString 25) ; returns "19"
(dotimes [i 20]
(println (Integer/toHexString i)))</
=={{header|Common Lisp}}==
<
(format t " ~6B ~3O ~2D ~2X~%" n n n n))</
=={{header|D}}==
<
void main() {
Line 425:
foreach (i; 0 .. 34)
writefln(" %6b %6o %6d %6x", i, i, i, i);
}</
{{out}}
<pre>Base: 2 8 10 16
Line 468:
{{libheader|Tango}}
<
Stdout.formatln ("{:b8} {:o3} {} {:x2}", i, i, i, i);</
=={{header|Dc}}==
<
[
2o lpx
Line 482:
1+ d21>b
]sb
1 lbx</
Bases above 16 print blank separated "digits" (in decimal)
{{out}}
Line 507:
=={{header|E}}==
<
for base in [2, 8, 10, 12, 16, 36] {
def s := value.toString(base)
Line 513:
}
println()
}</
=={{header|Elixir}}==
<
{{out}}
Line 564:
=={{header|Euphoria}}==
<
printf(1,"%6d %6x %6o\n",{i,i,i})
end for</
=={{header|F_Sharp|F#}}==
<p>Base 8, 10 and 16 can be output by <code>printf</code></p>
<
ns |> Seq.iter (fun n -> printfn " %3o %2d %2X" n n n)</
{{out}}
<pre> 36 30 1E
Line 578:
41 33 21</pre>
<p>The .NET library <code>System.Convert</code> is able to also convert from and to base 2</p>
<
ns |> Seq.map (fun n -> Seq.initInfinite (fun i -> n))
|> Seq.map (fun s -> Seq.zip s bases)
|> Seq.map (Seq.map System.Convert.ToString >> Seq.toList)
|> Seq.iter (fun s -> (printfn "%6s %2s %2s %2s" s.[0] s.[1] s.[2] s.[3]))</
{{out}}
<pre> 11110 36 30 1e
Line 591:
=={{header|Factor}}==
<
<pre style="height:30ex;overflow:scroll">
100101101011010000111
Line 633:
{{works with|GNU Forth}}
GNU Forth has convenience functions for printing an integer in decimal or hex, regardless of the current BASE.
<
main
...
11 $B
...</
This is not standardized because such functions are very easy to define as needed:
<
: oct. ( n -- ) 8 base. ;
: bin. ( n -- ) 2 base. ;</
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
write(*, "(b6, o4, i4, z4)") n, n, n, n
end do</
=={{header|FreeBASIC}}==
FreeBASIC has built in functions called Hex, Str, Oct and Bin which convert decimal numbers into hexadecimal, decimal,
octal and binary strings respectively. Here's an example:
<
Dim ui(1 To 4) As UInteger = {10, 26, 52, 100}
Line 661:
Next
Sleep</
{{out}}
Line 675:
=={{header|Gema}}==
After decimal numbers in the input stream, add hexadecimal and octal of the same number in the output stream. Also after hexadecimal add decimal and octal, and after octal add decimal and hexadecimal.
<
0<D>=$0 (@radix{8;10;$1}, 0x@radix{8;16;$1})
<D>=$0 (0x@radix{10;16;$1}, 0@radix{10;8;$1})</
Invocation and sample input and output
<pre>$ gema -p radix.gema
Line 684:
=={{header|Go}}==
<
import (
Line 708:
// There no equivalent for big ints.
fmt.Println(strconv.FormatInt(1313, 19))
}</
{{out}}
<pre>
Line 723:
=={{header|Haskell}}==
<
main :: IO ()
main = mapM_ f [0..33] where
f :: Int -> IO ()
f n = printf " %3o %2d %2X\n" n n n -- binary not supported</
alternately, without <code>Text.Printf</code>:
<
main :: IO ()
main = mapM_ f [0..33] where
f :: Int -> IO ()
f n = putStrLn $ " " ++ showOct n "" ++ " " ++ show n ++ " " ++ showHex n ""</
Or, generalising and tabulating a little:
<
import Data.Array (Array, listArray, (!))
import Data.Monoid ((<>))
Line 778:
mapM_
putStrLn
(table " " (([fmap show, fmap $ const "----"] <*> [bases]) <> tableRows))</
{{Out}}
<pre> 2 7 8 10 12 16 32
Line 817:
=={{header|HicEst}}==
<
WRITE(Format="b6.0, o4.0, i4.0, z4.0") n, n, n, n
ENDDO</
=={{header|Icon}} and {{header|Unicon}}==
Strictly speaking output conversion to different representations isn't built-in to Icon and Unicon; however, printf is included as part of the standard library.
<
write("Non-decimal radices/Output")
every i := 255 | 2 | 5 | 16 do {
Line 832:
printf("%%i = %i\n",i) # image format
}
end</
{{libheader|Icon Programming Library}}
Line 849:
J can natively break out numbers using a specific base
<
1 1 0 0
3 #.inv 100
1 0 2 0 1
16 #.inv 180097588
10 11 12 1 2 3 4</
However, this numeric representation would not satisfy most people's idea of "formatting", for most bases. It might be useful, however, for bases less than 10:
<
7 6 5 1
-.&' '": 8 #.inv 4009
7651</
J also includes some explicit support for hexadecimal numbers
<
hfd 180097588
ABC1234</
(and a few other hexadecimal related mechanisms which are not relevant here.)
=={{header|Java}}==
<
for(int a= 0;a < 33;a++){
System.out.println(Integer.toBinaryString(a));
Line 879:
System.out.printf("%3o %2d %2x\n",a ,a ,a); //printf like the other languages; binary not supported
}
}</
=={{header|JavaScript}}==
The <code><i>number</i>.toString(<i>radix</i>)</code> method produces a string representation of a number in any radix between 2 and 36.
<
for (var n = 0; n <= 33; n++) {
var row = [];
Line 890:
row.push( n.toString(bases[i]) );
print(row.join(', '));
}</
outputs
Line 929:
=={{header|Julia}}==
<
println("Primes ≤ $hi written in common bases.")
Line 936:
@printf("%8s%8s%8s%8s\n", bin(i), oct(i), dec(i), hex(i))
end
</
<pre>
Primes ≤ 50 written in common bases.
Line 958:
=={{header|Klingphix}}==
<
33 [
Line 964:
] for
"End " input</
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 978:
println()
}
}</
{{out}}
Line 1,024:
=={{header|Locomotive Basic}}==
<
20 PRINT i,BIN$(i),HEX$(i)
30 NEXT</
Output:
Line 1,052:
=={{header|Lua}}==
<
print( string.format( "%o \t %d \t %x", i, i, i ) )
end</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
{{out}}
<pre>1 1 1 1
Line 1,080:
=={{header|MATLAB}} / {{header|Octave}}==
<
Output:
<pre> 1 1 1
Line 1,104:
=={{header|Modula-3}}==
<
IMPORT IO, Fmt;
Line 1,115:
IO.Put("\n");
END;
END Conv.</
Output:
<pre style="height:30ex;overflow:scroll">
Line 1,154:
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
Line 1,192:
fm.format("[Base 16=%1$8x,Base 10=%1$8d,Base 8=%1$8o,Base 2=%2$20s]", [Object Long(n_), String('_')])
return fb.toString()
</syntaxhighlight>
'''Output:'''
<pre style="height:30ex; overflow:scroll;">
Line 1,230:
=={{header|Nim}}==
<
for i in 0..33:
echo toBin(i, 6)," ",toOct(i, 3)," ",align($i,2)," ",toHex(i,2)</
Output:
<pre>000000 000 0 00
Line 1,271:
=={{header|OCaml}}==
<
Printf.printf " %3o %2d %2X\n" n n n (* binary not supported *)
done</
=={{header|PARI/GP}}==
The only bases supported by the language itself (as opposed to custom functions) are binary and decimal.
<
n=binary(n);
for(i=1,#n,print1(n[i]))
Line 1,283:
printdecimal(n)={
print1(n)
};</
=={{header|Perl}}==
<
printf " %6b %3o %2d %2X\n", $n, $n, $n, $n;
}</
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">32</span> <span style="color: #008080;">by</span> <span style="color: #000000;">10</span> <span style="color: #008080;">do</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;">"decimal:%3d hex:%3x octal:%3o binary:%7b\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 1,306:
=={{header|Phixmonti}}==
<
dup "decimal: " print print " bin: " print 8 int>bit print nl
endfor</
=={{header|PHP}}==
<
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?></
<
foreach (range(0, 33) as $n) {
printf(" %6b %3o %2d %2X\n", $n, $n, $n, $n);
}
?></
=={{header|PicoLisp}}==
<
(when (>= N Base)
(printNumber (/ N Base) Base) )
Line 1,334:
(prinl)
(printNumber 123456789012345678901234567890 36))
(prinl)</
Output:
<pre>1a
Line 1,340:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
get list (n);
put skip list (n); /* Prints N in decimal */
put skip edit (n) (B); /* prints N as a bit string, N > 0 */
</syntaxhighlight>
=={{header|PowerShell}}==
The .NET class <code>Convert</code> handles conversions in binary, octal, decimal and hexadecimal. Furthermore, format strings may be used for hexadecimal conversion.
<
"Base 2: " + [Convert]::ToString($n, 2)
"Base 8: " + [Convert]::ToString($n, 8)
Line 1,356:
"Base 16: " + [Convert]::ToString($n, 16)
"Base 16: " + ("{0:X}" -f $n)
}</
=={{header|PureBasic}}==
<
Bin$=RSet(Bin(i),8,"0") ;- Convert to wanted type & pad with '0'
Hex$=RSet(Hex(i),4,"0")
Dec$=RSet(Str(i),3)
PrintN(Dec$+" decimal = %"+Bin$+" = $"+Hex$+".")
Next</
105 decimal = %01101001 = $0069.
Line 1,381:
{{works with|Python|2.6}}
Binary (b), Octal (o), Decimal (d), and Hexadecimal (X and x) are supported by the [http://www.python.org/dev/peps/pep-3101/ format]method of a string
<div style="height:30ex;overflow:scroll"><
print " {0:6b} {1:3o} {2:2d} {3:2X}".format(n, n, n, n)
#The following would give the same output, and,
Line 1,422:
100000 40 32 20
100001 41 33 21
>>></
{{works with|Python|2.5}}
Octal (o), Decimal (d), and Hexadecimal (X and x), but not binary are supported by the string modulo operator, %:
<
print " %3o %2d %2X" % (n, n, n)</
----
For each of these bases there is also a built-in function that will convert it to a string with the proper prefix appended, so that it is a valid Python expression:
<
#Python 3.x:
print(bin(n), oct(n), n, hex(n)) # bin() only available in Python 3.x and 2.6
Line 1,438:
#Python 2.x:
#print oct(n), n, hex(n)
# output: 041 33 0x21</
=={{header|R}}==
Conversion to and from binary does not have built-in support.
<
as.octmode(x)
# dec to hex
Line 1,449:
as.integer(x)
# or
as.numeric(x)</
=={{header|Racket}}==
<
#lang racket
Line 1,466:
;; "3a" "69" "b8" "38" "7b" "47" "f6" "96" "36" "i5" "d5" "85" "35"
;; "n4" "j4" "f4" "b4" "74" "34" "u3" "r3" "o3" "l3" "i3" "f3")
</syntaxhighlight>
=={{header|Raku}}==
Line 1,473:
Calling the <code>.base</code> method on a number returns a string. It can handle all bases between 2 and 36:
<syntaxhighlight lang="raku"
say 30.base(8); # "36"
say 30.base(10); # "30"
say 30.base(16); # "1E"
say 30.base(30); # "10"</
Alternatively, <code>printf</code> can be used for some common number bases:
<syntaxhighlight lang="raku"
printf " %6b %3o %2d %2X\n", $n xx 4;
}</
=={{header|REXX}}==
Line 1,490:
<br><br>The reason for the apparent complexity of the '''D2B''' function is to handle the special case of
<br>zero (with regards to striping leading zeroes from the converted number)..
<
do j=0 to 50 /*show some low-value num conversions*/
Line 1,499:
exit /*stick a fork in it, we're done.*/
/*────────────────────────────D2B subroutine────────────────────────────*/
d2b: return word(strip(x2b(d2x(arg(1))),'L',0) 0,1) /*convert dec──►bin*/</
'''output'''
<pre style="height:20ex">
Line 1,559:
<br><br>Of course, using base 256 is hampered in ASCII machines in that some lower values are
<br>interpreted by the operating system as control characters and therefore aren't displayed as their (true) glyph.
<
do j=14 to 67 /*display some lower-value numbers. */
Line 1,569:
exit /*stick a fork in it, we're done.*/
/*────────────────────────────D2B subroutine────────────────────────────*/
d2b: return word(strip(x2b(d2x(arg(1))),'L',0) 0,1) /*convert dec──►bin*/</
'''output'''
<pre style="height:20ex">
Line 1,629:
=={{header|Ring}}==
<
# Project : Non Decimal radices/Output
Line 1,638:
see upper(hex(43981)) + nl
see upper(hex(-1)) + nl
</syntaxhighlight>
Output:
<pre>
Line 1,649:
=={{header|Ruby}}==
<
puts " %6b %3o %2d %2X" % [n, n, n, n]
end
puts
[2,8,10,16,36].each {|i| puts " 100.to_s(#{i}) => #{100.to_s(i)}"}</
{{out}}
<div style="height:30ex;overflow:scroll">
Line 1,699:
=={{header|Rust}}==
<
// To render the number as string, use format! macro instead
println!("Binary: {:b}", 0xdeadbeefu32);
Line 1,710:
println!("Uppercase hexadecimal: {:X}", 0xdeadbeefu32);
println!("Uppercase hexadecimal with 0x prefix: {:#X}", 0xdeadbeefu32);
}</
=={{header|Run BASIC}}==
<
print asc("X") ' convert to ascii
print chr$(169) ' ascii to character
Line 1,720:
print str$(467) ' decimal to string
print val("27") ' string to decimal
</syntaxhighlight>
=={{header|Scala}}==
<
val radices = List(2, 8, 10, 16, 19, 36)
for (base <- radices) print(f"$base%6d")
Line 1,731:
eol = if (radix == radices.last) '\n' else '\0'
) print(f"${i.toString(radix)}%6s$eol")
}</
=={{header|Scheme}}==
<
((>= i 33))
(display (number->string i 2)) ; binary
Line 1,743:
(display " ")
(display (number->string i 16)) ; hex
(newline))</
=={{header|Seed7}}==
Line 1,754:
The [http://seed7.sourceforge.net/libraries/string.htm#%28in_string%29lpad%28in_integer%29 lpad] operator
is used to pad the result of the ''radix'' operator at the left side. The padding is done with spaces.
<
const proc: main is func
Line 1,765:
i radix 16 lpad 6);
end for;
end func;</
=={{header|Sidef}}==
<
printf(" %6b %3o %2d %2X\n", ([n]*4)...);
}</
=={{header|Smalltalk}}==
The radix can be from 2 to 49 and its value is prepended to the string followed by "r".
<
('%1 %2 %3' % { i printStringRadix: 8. i printStringRadix: 16. i printStringRadix: 2 })
printNl.
].</
=={{header|Standard ML}}==
<
fun loop i =
if i < 34 then (
Line 1,791:
in
loop 0
end</
=={{header|Tcl}}==
The <code>format</code> command supports conversions to octal, decimal, and hex:
<
puts [format " %3o %2d %2X" $n $n $n]
}</
<!--The following should be moved to: [[Number base conversion]]
Conversion to binary requires a procedure. Here's two ways to do it:
<
proc int2bits {i} {
string map {0 000 1 001 2 010 3 011 4 100 5 101 6 110 7 111} [format %o $i]
Line 1,812:
binary scan [binary format I1 $i] B* x
return $x
}</
-->
Line 1,820:
Bases 2, 10, and 16 are supported. The base is controlled by a global ''mode''.
<
getMode("Base")→old
setMode("Base", "BIN")
Line 1,828:
setMode("Base", "DEC")
Disp string(16)
setMode("Base", old)</
Output:
<
0h10
16</
=={{header|Wren}}==
{{libheader|Wren-fmt}}
Wren has no non-decimal number conversions in its standard library so this uses a module I wrote myself to reproduce the Haskell table.
<
System.print(" 2 7 8 10 12 16 32")
Line 1,852:
var b32 = Fmt.s(4, Conv.Itoa(i, 32))
System.print("%(b2) %(b7) %(b8) %(b10) %(b12) %(b16) %(b32)")
}</
{{out}}
Line 1,894:
=={{header|XPL0}}==
<
int N;
[N:= 2;
Line 1,901:
N:= N*N;
until N=0;
]</
Output:
Line 1,913:
=={{header|Yabasic}}==
<
print "decimal: ", i, " hex: ", hex$(i), " bin: ", bin$(i)
next
</syntaxhighlight>
=={{header|zkl}}==
"%.nB" formats a [unsigned] number in base n (2-36). So
<
var fmt=[2..N].pump(String,"%%5.%dB".fmt); // %5.2B%5.3B%5.4B%5.5B ...
foreach n in (17){fmt.fmt(n.pump(N,List,n.fp(n)).xplode()).println()}</
{{out}}
<pre>
Line 1,943:
10000 121 100 31 24 22 20 17 16 15 14 13 12 11 10
</pre>
<
For binary, decimal and hex, you can also have [fixed, sorry Europe] separators:
<
"%,d".fmt(1234567) //-->"1,234,567"
"%,x".fmt(1234567) //-->"12|d6|87"</
|