Non-decimal radices/Output

From Rosetta Code

Jump to: navigation, search
Task
Non-decimal radices/Output
You are encouraged to solve this task according to the task description, using any language you may know.
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal.

Show how to print a small range of integers in some different bases, as supported by standard routines of your programming language. (Note: this is distinct from Number base conversion as a user-defined conversion function is not asked for.)

The reverse operation is Common number base parsing.

Contents

[edit] Ada

with Ada.Integer_Text_IO;  use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
 
procedure Test_Integer_Text_IO is
begin
for I in 1..33 loop
Put (I, Width =>3, Base=> 10);
Put (I, Width =>7, Base=> 16);
Put (I, Width =>6, Base=> 8);
New_Line;
end loop;
end Test_Integer_Text_IO;

Sample output:

  1  16#1#  8#1#
  2  16#2#  8#2#
  3  16#3#  8#3#
  4  16#4#  8#4#
  5  16#5#  8#5#
  6  16#6#  8#6#
  7  16#7#  8#7#
  8  16#8# 8#10#
  9  16#9# 8#11#
 10  16#A# 8#12#
 11  16#B# 8#13#
 12  16#C# 8#14#
 13  16#D# 8#15#
 14  16#E# 8#16#
 15  16#F# 8#17#
 16 16#10# 8#20#
 17 16#11# 8#21#
 18 16#12# 8#22#
 19 16#13# 8#23#
 20 16#14# 8#24#
 21 16#15# 8#25#
 22 16#16# 8#26#
 23 16#17# 8#27#
 24 16#18# 8#30#
 25 16#19# 8#31#
 26 16#1A# 8#32#
 27 16#1B# 8#33#
 28 16#1C# 8#34#
 29 16#1D# 8#35#
 30 16#1E# 8#36#
 31 16#1F# 8#37#
 32 16#20# 8#40#
 33 16#21# 8#41#

[edit] ALGOL 68

Translation of: C

Works with: ALGOL 68 version Revision 1 - no extensions to language used

Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny

main:(
FOR i TO 33 DO
printf(($10r6d," "16r6d," "8r6dl$, BIN i, BIN i, BIN i))
OD
)

Sample output:

000001 000001 000001
000002 000002 000002
000003 000003 000003
000004 000004 000004
000005 000005 000005
000006 000006 000006
000007 000007 000007
000008 000008 000010
000009 000009 000011
000010 00000a 000012
000011 00000b 000013
000012 00000c 000014
000013 00000d 000015
000014 00000e 000016
000015 00000f 000017
000016 000010 000020
000017 000011 000021
000018 000012 000022
000019 000013 000023
000020 000014 000024
000021 000015 000025
000022 000016 000026
000023 000017 000027
000024 000018 000030
000025 000019 000031
000026 00001a 000032
000027 00001b 000033
000028 00001c 000034
000029 00001d 000035
000030 00001e 000036
000031 00001f 000037
000032 000020 000040
000033 000021 000041

[edit] AutoHotkey

contributed by Laszlo on the ahk forum

MsgBox % BC("FF",16,3) ; -> 100110 in base 3 = FF in hex = 256 in base 10
 
BC(NumStr,InputBase=8,OutputBase=10) {
Static S = 12345678901234567890123456789012345678901234567890123456789012345
DllCall("msvcrt\_i64toa","Int64",DllCall("msvcrt\_strtoui64","Str",NumStr,"Uint",0,"UInt",InputBase,"CDECLInt64"),"Str",S,"UInt",OutputBase,"CDECL")
Return S
}

[edit] AWK

C's printf() is just exposed:

$ awk '{printf("%d 0%o 0x%x\n",$1,$1,$1)}'
10
10 012 0xa
16
16 020 0x10
255
255 0377 0xff

[edit] C

#include <stdio.h>
 
int main()
{
int i;
 
for(i=1; i <= 33; i++)
printf("%6d %6x %6o\n", i, i, i);
 
return 0;
}

Binary conversion using %b is not standard.

[edit] C++

#include <iostream>
#include <iomanip>
 
int main()
{
for (int i = 0; i <= 33; i++)
std::cout << std::setw(6) << std::dec << i << " "
<< std::setw(6) << std::hex << i << " "
<< std::setw(6) << std::oct << i << std::endl;
 
return 0;
}

Binary conversion is not standard.

[edit] Clojure

Clojure eschews duplicating functionality already present in Java when interop is sufficiently idiomatic:

(Integer/toBinaryString 25) ; returns "11001"
(Integer/toOctalString 25) ; returns "31"
(Integer/toHexString 25) ; returns "19"
 
(dotimes [i 20]
(println (Integer/toHexString i)))

[edit] Common Lisp

(loop for n from 0 to 33 do
(format t " ~6B ~3O ~2D ~2X~%" n n n n))

[edit] D

Works with: Tango

Number following formatting character is width. When no formatting character is specified it is inferred from variable's type.

for (int i = 0; i < 35; i++)
Stdout.formatln ("{:b8} {:o3} {} {:x2}", i, i, i, i);

[edit] E

for value in 0..33 {
for base in [2, 8, 10, 12, 16, 36] {
def s := value.toString(base)
print(" " * (8 - s.size()), s)
}
println()
}

[edit] Factor

1234567 2 36 [a,b] [ >base print ] with each
100101101011010000111
2022201111201
10231122013
304001232
42243331
13331215
4553207
2281451
1234567
773604
4b6547
342c19
241cb5
195be7
12d687
ed4ea
bdc71
98ig4
7e687
6769j
55kgf
49ahj
3h787
3407h
2i679
28jdj
206jj
1lhs8
1flm7
1adkn
15lk7
11bm4
vdwr
srsc
qglj

[edit] Forth

Works with: GNU Forth GNU Forth has convenience functions for printing an integer in decimal or hex, regardless of the current BASE.

: main 34 1 do cr i dec. i hex. loop ;
main
...
11 $B
...

This is not standardized because such functions are very easy to define as needed:

: base. ( n base -- ) base @ >r  base !  .  r> base ! ;
: oct. ( n -- ) 8 base. ;
: bin. ( n -- ) 2 base. ;

[edit] Fortran

Works with: Fortran version 90 and later

do n = 1, 33
write(*, "(b6, o4, i4, z4)") n, n, n, n
end do

[edit] Haskell

import Text.Printf
 
main :: IO ()
main = mapM_ f [0..33] where
f :: Int -> IO ()
f n = printf " %3o %2d %2X\n" n n n -- binary not supported

[edit] HicEst

DO n = 1, 33
WRITE(Format="b6.0, o4.0, i4.0, z4.0") n, n, n, n
ENDDO

[edit] J

J can natively break out numbers using a specific base

   2 #.inv 12
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:

   8 #.inv 4009
7 6 5 1
-.&' '": 8 #.inv 4009
7651

J also includes some explicit support for hexadecimal numbers

  require 'convert'
hfd 180097588
ABC1234

(and a few other hexadecimal related mechanisms which are not relevant here.)

[edit] Java

public static void main(String args[]){
for(int a= 0;a < 33;a++){
System.out.println(Integer.toBinaryString(a));
System.out.println(Integer.toOctalString(a));
System.out.println(Integer.toHexString(a));
//the above methods treat the integer as unsigned
//there are also corresponding Long.to***String() methods for long's.
 
System.out.printf("%3o %2d %2x\n",a ,a ,a); //printf like the other languages; binary not supported
}
}

[edit] JavaScript

The number.toString(radix) method produces a string representation of a number in any radix between 2 and 36.

var bases = [2, 8, 10, 16, 24];
for (var n = 0; n <= 33; n++) {
var row = [];
for (var i = 0; i < bases.length; i++)
row.push( n.toString(bases[i]) );
print(row.join(', '));
}

outputs

0, 0, 0, 0, 0
1, 1, 1, 1, 1
10, 2, 2, 2, 2
11, 3, 3, 3, 3
100, 4, 4, 4, 4
101, 5, 5, 5, 5
110, 6, 6, 6, 6
111, 7, 7, 7, 7
1000, 10, 8, 8, 8
1001, 11, 9, 9, 9
1010, 12, 10, a, a
1011, 13, 11, b, b
1100, 14, 12, c, c
1101, 15, 13, d, d
1110, 16, 14, e, e
1111, 17, 15, f, f
10000, 20, 16, 10, g
10001, 21, 17, 11, h
10010, 22, 18, 12, i
10011, 23, 19, 13, j
10100, 24, 20, 14, k
10101, 25, 21, 15, l
10110, 26, 22, 16, m
10111, 27, 23, 17, n
11000, 30, 24, 18, 10
11001, 31, 25, 19, 11
11010, 32, 26, 1a, 12
11011, 33, 27, 1b, 13
11100, 34, 28, 1c, 14
11101, 35, 29, 1d, 15
11110, 36, 30, 1e, 16
11111, 37, 31, 1f, 17
100000, 40, 32, 20, 18
100001, 41, 33, 21, 19

[edit] Modula-3

MODULE Conv EXPORTS Main;
 
IMPORT IO, Fmt;
 
BEGIN
FOR i := 1 TO 33 DO
IO.Put(Fmt.Int(i, base := 10) & " ");
IO.Put(Fmt.Int(i, base := 16) & " ");
IO.Put(Fmt.Int(i, base := 8) & " ");
IO.Put("\n");
END;
END Conv.

Output:

1 1 1 
2 2 2 
3 3 3 
4 4 4 
5 5 5 
6 6 6 
7 7 7 
8 8 10 
9 9 11 
10 a 12 
11 b 13 
12 c 14 
13 d 15 
14 e 16 
15 f 17 
16 10 20 
17 11 21 
18 12 22 
19 13 23 
20 14 24 
21 15 25 
22 16 26 
23 17 27 
24 18 30 
25 19 31 
26 1a 32 
27 1b 33 
28 1c 34 
29 1d 35 
30 1e 36 
31 1f 37 
32 20 40 
33 21 41

[edit] OCaml

for n = 0 to 33 do
Printf.printf " %3o %2d %2X\n" n n n (* binary not supported *)
done

[edit] Perl

foreach my $n (0..33) {
printf " %6b %3o %2d %2X\n", $n, $n, $n, $n;
}

[edit] PHP

<?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($n), "\n";
}
?>
<?php
foreach (range(0, 33) as $n) {
printf(" %6b %3o %2d %2X\n", $n, $n, $n, $n);
}
?>

[edit] 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 */
 

[edit] PicoLisp

(de printNumber (N Base)
(when (>= N Base)
(printNumber (/ N Base) Base) )
(let C (% N Base)
(and (> C 9) (inc 'C 39))
(prin (char (+ C `(char "0")))) ) )
 
(printNumber 26 16))
(prinl)
(printNumber 123456789012345678901234567890 36))
(prinl)

Output:

1a
byw97um9s91dlz68tsi

[edit] PowerShell

The .NET class Convert handles conversions in binary, octal, decimal and hexadecimal. Furthermore, format strings may be used for hexadecimal conversion.

foreach ($n in 0..33) {
"Base 2: " + [Convert]::ToString($n, 2)
"Base 8: " + [Convert]::ToString($n, 8)
"Base 10: " + $n
"Base 10: " + [Convert]::ToString($n, 10)
"Base 10: " + ("{0:D}" -f $n)
"Base 16: " + [Convert]::ToString($n, 16)
"Base 16: " + ("{0:X}" -f $n)
}

[edit] PureBasic

For i=105 To 115
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.
106 decimal = %01101010 = $006A.
107 decimal = %01101011 = $006B.
108 decimal = %01101100 = $006C.
109 decimal = %01101101 = $006D.
110 decimal = %01101110 = $006E.
111 decimal = %01101111 = $006F.
112 decimal = %01110000 = $0070.
113 decimal = %01110001 = $0071.
114 decimal = %01110010 = $0072.
115 decimal = %01110011 = $0073.

[edit] Python

Works with: Python version 2.6 Binary (b), Octal (o), Decimal (d), and Hexadecimal (X and x) are supported by the formatmethod of a string

>>> for n in range(34):
print " {0:6b} {1:3o} {2:2d} {3:2X}".format(n, n, n, n)
#The following would give the same output, and,
#due to the outer brackets, works with Python 3.0 too
#print ( " {n:6b} {n:3o} {n:2d} {n:2X}".format(n=n) )
 
 
0 0 0 0
1 1 1 1
10 2 2 2
11 3 3 3
100 4 4 4
101 5 5 5
110 6 6 6
111 7 7 7
1000 10 8 8
1001 11 9 9
1010 12 10 A
1011 13 11 B
1100 14 12 C
1101 15 13 D
1110 16 14 E
1111 17 15 F
10000 20 16 10
10001 21 17 11
10010 22 18 12
10011 23 19 13
10100 24 20 14
10101 25 21 15
10110 26 22 16
10111 27 23 17
11000 30 24 18
11001 31 25 19
11010 32 26 1A
11011 33 27 1B
11100 34 28 1C
11101 35 29 1D
11110 36 30 1E
11111 37 31 1F
100000 40 32 20
100001 41 33 21
>>>

Works with: Python version 2.5 Octal (o), Decimal (d), and Hexadecimal (X and x), but not binary are supported by the string modulo operator, %:

for n in range(34):
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:

n = 33
#Python 3.x:
print(bin(n), oct(n), n, hex(n)) # bin() only available in Python 3.x and 2.6
# output: 0b100001 0o41 33 0x21
 
#Python 2.x:
#print oct(n), n, hex(n)
# output: 041 33 0x21

[edit] R

Conversion to and from binary does not have built-in support.

# dec to oct
as.octmode(x)
# dec to hex
as.hexmode(x)
# oct or hex to dec
as.integer(x)
# or
as.numeric(x)

[edit] Ruby

irb(main):001:0> for n in 0..33
irb(main):002:1> puts " %6b %3o %2d %2X" % [n, n, n, n]
irb(main):003:1> end
0 0 0 0
1 1 1 1
10 2 2 2
11 3 3 3
100 4 4 4
101 5 5 5
110 6 6 6
111 7 7 7
1000 10 8 8
1001 11 9 9
1010 12 10 A
1011 13 11 B
1100 14 12 C
1101 15 13 D
1110 16 14 E
1111 17 15 F
10000 20 16 10
10001 21 17 11
10010 22 18 12
10011 23 19 13
10100 24 20 14
10101 25 21 15
10110 26 22 16
10111 27 23 17
11000 30 24 18
11001 31 25 19
11010 32 26 1A
11011 33 27 1B
11100 34 28 1C
11101 35 29 1D
11110 36 30 1E
11111 37 31 1F
100000 40 32 20
100001 41 33 21
=> 0..33

[edit] Scheme

(do ((i 0 (+ i 1)))
((>= i 33))
(display (number->string i 2)) ; binary
(display " ")
(display (number->string i 8)) ; octal
(display " ")
(display (number->string i 10)) ; decimal, the "10" is optional
(display " ")
(display (number->string i 16)) ; hex
(newline))

[edit] Standard ML

let
fun loop i =
if i < 34 then (
print (Int.fmt StringCvt.BIN i ^ "\t"
^ Int.fmt StringCvt.OCT i ^ "\t"
^ Int.fmt StringCvt.DEC i ^ "\t"
^ Int.fmt StringCvt.HEX i ^ "\n");
loop (i+1)
) else ()
in
loop 0
end

[edit] Tcl

The format command supports conversions to octal, decimal, and hex:

for {set n 0} {$n <= 33} {incr n} {
puts [format " %3o %2d %2X" $n $n $n]
}


[edit] TI-89 BASIC

Bases 2, 10, and 16 are supported. The base is controlled by a global mode.

Local old
getMode("Base")→old
setMode("Base", "BIN")
Disp string(16)
setMode("Base", "HEX")
Disp string(16)
setMode("Base", "DEC")
Disp string(16)
setMode("Base", old)

Output:

0b10000
0h10
16
Personal tools