Binary digits: Difference between revisions

Content added Content deleted
(→‎{{header|Commodore BASIC}}: make subroutine more general (create string, no print), use READ loop with DATA for demo, add comment on FOR STEP 0 loop.)
m (syntax highlighting fixup automation)
Line 17: Line 17:


=={{header|0815}}==
=={{header|0815}}==
<lang 0815>}:r:|~ Read numbers in a loop.
<syntaxhighlight lang=0815>}:r:|~ Read numbers in a loop.
}:b: Treat the queue as a stack and
}:b: Treat the queue as a stack and
<:2:= accumulate the binary digits
<:2:= accumulate the binary digits
Line 28: Line 28:
^:p:
^:p:
<:a:~$ Output a newline.
<:a:~$ Output a newline.
^:r:</lang>
^:r:</syntaxhighlight>


{{out}}
{{out}}
Line 34: Line 34:
Note that 0815 reads numeric input in hexadecimal.
Note that 0815 reads numeric input in hexadecimal.


<lang bash>echo -e "5\n32\n2329" | 0815 bin.0
<syntaxhighlight lang=bash>echo -e "5\n32\n2329" | 0815 bin.0
101
101
110010
110010
10001100101001</lang>
10001100101001</syntaxhighlight>


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>L(n) [0, 5, 50, 9000]
<syntaxhighlight lang=11l>L(n) [0, 5, 50, 9000]
print(‘#4 = #.’.format(n, bin(n)))</lang>
print(‘#4 = #.’.format(n, bin(n)))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 51: Line 51:


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
<lang 360asm>* Binary digits 27/08/2015
<syntaxhighlight lang=360asm>* Binary digits 27/08/2015
BINARY CSECT
BINARY CSECT
USING BINARY,R12
USING BINARY,R12
Line 93: Line 93:
CBIN DC CL32' ' binary value
CBIN DC CL32' ' binary value
YREGS
YREGS
END BINARY</lang>
END BINARY</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 122: Line 122:
strout = $cb1e
strout = $cb1e
</pre>
</pre>
<lang 6502asm>
<syntaxhighlight lang=6502asm>
; C64 - Binary digits
; C64 - Binary digits
; http://rosettacode.org/wiki/Binary_digits
; http://rosettacode.org/wiki/Binary_digits
Line 213: Line 213:
binstr .repeat 16, $00 ; reserve 16 bytes for the binary digits
binstr .repeat 16, $00 ; reserve 16 bytes for the binary digits
.byte $0d, $00 ; newline + null terminator
.byte $0d, $00 ; newline + null terminator
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 230: Line 230:


=={{header|8080 Assembly}}==
=={{header|8080 Assembly}}==
<lang 8080asm>bdos: equ 5h ; CP/M system call
<syntaxhighlight lang=8080asm>bdos: equ 5h ; CP/M system call
puts: equ 9h ; Print string
puts: equ 9h ; Print string
org 100h
org 100h
Line 261: Line 261:
jmp binlp ; Otherwise, do next bit
jmp binlp ; Otherwise, do next bit
binstr: db '0000000000000000' ; Placeholder for string
binstr: db '0000000000000000' ; Placeholder for string
binend: db 13,10,'$' ; end with \r\n </lang>
binend: db 13,10,'$' ; end with \r\n </syntaxhighlight>


{{out}}
{{out}}
Line 272: Line 272:


=={{header|8086 Assembly}}==
=={{header|8086 Assembly}}==
<lang asm> .model small
<syntaxhighlight lang=asm> .model small
.stack 1024
.stack 1024
.data
.data
Line 356: Line 356:
pop ax
pop ax
ret
ret
PrintBinary_NoLeadingZeroes endp</lang>
PrintBinary_NoLeadingZeroes endp</syntaxhighlight>


=={{header|8th}}==
=={{header|8th}}==
<lang forth>
<syntaxhighlight lang=forth>
2 base drop
2 base drop
#50 . cr
#50 . cr
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 370: Line 370:
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<lang AArch64 Assembly>
<syntaxhighlight lang=AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program binarydigit.s */
/* program binarydigit.s */
Line 524: Line 524:
.include "../includeARM64.inc"
.include "../includeARM64.inc"


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 534: Line 534:


=={{header|ACL2}}==
=={{header|ACL2}}==
<lang Lisp>(include-book "arithmetic-3/top" :dir :system)
<syntaxhighlight lang=Lisp>(include-book "arithmetic-3/top" :dir :system)


(defun bin-string-r (x)
(defun bin-string-r (x)
Line 548: Line 548:
(if (zp x)
(if (zp x)
"0"
"0"
(bin-string-r x)))</lang>
(bin-string-r x)))</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC PrintBinary(CARD v)
<syntaxhighlight lang=Action!>PROC PrintBinary(CARD v)
CHAR ARRAY a(16)
CHAR ARRAY a(16)
BYTE i=[0]
BYTE i=[0]
Line 581: Line 581:
PutE()
PutE()
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Binary_digits.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Binary_digits.png Screenshot from Atari 8-bit computer]
Line 593: Line 593:
=={{header|Ada}}==
=={{header|Ada}}==


<lang Ada>with ada.text_io; use ada.text_io;
<syntaxhighlight lang=Ada>with ada.text_io; use ada.text_io;
procedure binary is
procedure binary is
bit : array (0..1) of character := ('0','1');
bit : array (0..1) of character := ('0','1');
Line 605: Line 605:
put_line ("Output for" & test'img & " is " & bin_image (test));
put_line ("Output for" & test'img & " is " & bin_image (test));
end loop;
end loop;
end binary;</lang>
end binary;</syntaxhighlight>


{{out}}
{{out}}
Line 615: Line 615:


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>o_xinteger(2, 0);
<syntaxhighlight lang=aime>o_xinteger(2, 0);
o_byte('\n');
o_byte('\n');
o_xinteger(2, 5);
o_xinteger(2, 5);
Line 621: Line 621:
o_xinteger(2, 50);
o_xinteger(2, 50);
o_byte('\n');
o_byte('\n');
o_form("/x2/\n", 9000);</lang>
o_form("/x2/\n", 9000);</syntaxhighlight>
{{out}}
{{out}}
<pre>0
<pre>0
Line 632: Line 632:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.3.3 algol68g-2.3.3].}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.3.3 algol68g-2.3.3].}}
{{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] - due to use of '''format'''[ted] ''transput''.}}
{{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] - due to use of '''format'''[ted] ''transput''.}}
'''File: Binary_digits.a68'''<lang algol68>#!/usr/local/bin/a68g --script #
'''File: Binary_digits.a68'''<syntaxhighlight lang=algol68>#!/usr/local/bin/a68g --script #


printf((
printf((
Line 645: Line 645:
50, " => ", []BOOL(BIN 50)[bits width-6+1:], new line,
50, " => ", []BOOL(BIN 50)[bits width-6+1:], new line,
9000, " => ", []BOOL(BIN 9000)[bits width-14+1:], new line
9000, " => ", []BOOL(BIN 9000)[bits width-14+1:], new line
))</lang>
))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 657: Line 657:


=={{header|ALGOL-M}}==
=={{header|ALGOL-M}}==
<lang algolm>begin
<syntaxhighlight lang=algolm>begin
procedure writebin(n);
procedure writebin(n);
integer n;
integer n;
Line 674: Line 674:
writebin(50);
writebin(50);
writebin(9000);
writebin(9000);
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 684: Line 684:


A builtin function. Produces a boolean array.
A builtin function. Produces a boolean array.
<lang apl>base2←2∘⊥⍣¯1</lang>
<syntaxhighlight lang=apl>base2←2∘⊥⍣¯1</syntaxhighlight>




Line 690: Line 690:


Produces a boolean array.
Produces a boolean array.
<lang apl>base2 ← {((⌈2⍟⍵+1)⍴2)⊤⍵}</lang>
<syntaxhighlight lang=apl>base2 ← {((⌈2⍟⍵+1)⍴2)⊤⍵}</syntaxhighlight>


NOTE: Both versions above will yield an empty boolean array for 0.
NOTE: Both versions above will yield an empty boolean array for 0.
Line 706: Line 706:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang=algolw>begin
% prints an integer in binary - the number must be greater than zero %
% prints an integer in binary - the number must be greater than zero %
procedure printBinaryDigits( integer value n ) ;
procedure printBinaryDigits( integer value n ) ;
Line 729: Line 729:
end
end


end.</lang>
end.</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
Line 737: Line 737:


(The generic showIntAtBase here, which allows us to specify the digit set used (e.g. upper or lower case in hex, or different regional or other digit sets generally), is a rough translation of Haskell's Numeric.showintAtBase)
(The generic showIntAtBase here, which allows us to specify the digit set used (e.g. upper or lower case in hex, or different regional or other digit sets generally), is a rough translation of Haskell's Numeric.showintAtBase)
<lang applescript>---------------------- BINARY STRING -----------------------
<syntaxhighlight lang=applescript>---------------------- BINARY STRING -----------------------


-- showBin :: Int -> String
-- showBin :: Int -> String
Line 833: Line 833:
on unlines(xs)
on unlines(xs)
intercalate(linefeed, xs)
intercalate(linefeed, xs)
end unlines</lang>
end unlines</syntaxhighlight>
<pre>5 -> 101
<pre>5 -> 101
50 -> 110010
50 -> 110010
Line 839: Line 839:


Or using:
Or using:
<lang applescript>-- showBin :: Int -> String
<syntaxhighlight lang=applescript>-- showBin :: Int -> String
on showBin(n)
on showBin(n)
script binaryChar
script binaryChar
Line 847: Line 847:
end script
end script
showIntAtBase(2, binaryChar, n, "")
showIntAtBase(2, binaryChar, n, "")
end showBin</lang>
end showBin</syntaxhighlight>
{{Out}}
{{Out}}
<pre>5 -> 一〇一
<pre>5 -> 一〇一
Line 857: Line 857:
At its very simplest, an AppleScript solution would look something like this:
At its very simplest, an AppleScript solution would look something like this:


<lang applescript>on intToBinary(n)
<syntaxhighlight lang=applescript>on intToBinary(n)
set binary to (n mod 2 div 1) as text
set binary to (n mod 2 div 1) as text
set n to n div 2
set n to n div 2
Line 871: Line 871:
intToBinary(5) & linefeed & ¬
intToBinary(5) & linefeed & ¬
intToBinary(50) & linefeed & ¬
intToBinary(50) & linefeed & ¬
intToBinary(9000) & linefeed</lang>
intToBinary(9000) & linefeed</syntaxhighlight>


Building a list of single-digit values instead and coercing that at the end can be a tad faster, but execution can be four or five times as fast when groups of text (or list) operations are replaced with arithmetic:
Building a list of single-digit values instead and coercing that at the end can be a tad faster, but execution can be four or five times as fast when groups of text (or list) operations are replaced with arithmetic:


<lang applescript>on intToBinary(n)
<syntaxhighlight lang=applescript>on intToBinary(n)
set binary to ""
set binary to ""
repeat
repeat
Line 897: Line 897:
intToBinary(5) & linefeed & ¬
intToBinary(5) & linefeed & ¬
intToBinary(50) & linefeed & ¬
intToBinary(50) & linefeed & ¬
intToBinary(9000) & linefeed</lang>
intToBinary(9000) & linefeed</syntaxhighlight>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<lang ARM Assembly>
<syntaxhighlight lang=ARM Assembly>


/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
Line 1,065: Line 1,065:
.Ls_magic_number_10: .word 0x66666667
.Ls_magic_number_10: .word 0x66666667


</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>print as.binary 5
<syntaxhighlight lang=rebol>print as.binary 5
print as.binary 50
print as.binary 50
print as.binary 9000</lang>
print as.binary 9000</syntaxhighlight>
{{out}}
{{out}}
Line 1,079: Line 1,079:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>MsgBox % NumberToBinary(5) ;101
<syntaxhighlight lang=AutoHotkey>MsgBox % NumberToBinary(5) ;101
MsgBox % NumberToBinary(50) ;110010
MsgBox % NumberToBinary(50) ;110010
MsgBox % NumberToBinary(9000) ;10001100101000
MsgBox % NumberToBinary(9000) ;10001100101000
Line 1,088: Line 1,088:
Result := (InputNumber & 1) . Result, InputNumber >>= 1
Result := (InputNumber & 1) . Result, InputNumber >>= 1
Return, Result
Return, Result
}</lang>
}</syntaxhighlight>


=={{header|AutoIt}}==
=={{header|AutoIt}}==
<lang autoit>
<syntaxhighlight lang=autoit>
ConsoleWrite(IntToBin(50) & @CRLF)
ConsoleWrite(IntToBin(50) & @CRLF)


Line 1,107: Line 1,107:
Return $r
Return $r
EndFunc ;==>IntToBin
EndFunc ;==>IntToBin
</syntaxhighlight>
</lang>


=={{header|AWK}}==
=={{header|AWK}}==
<lang awk>BEGIN {
<syntaxhighlight lang=awk>BEGIN {
print tobinary(5)
print tobinary(5)
print tobinary(50)
print tobinary(50)
Line 1,132: Line 1,132:
}
}
return outstr
return outstr
}</lang>
}</syntaxhighlight>


=={{header|Axe}}==
=={{header|Axe}}==
This example builds a string backwards to ensure the digits are displayed in the correct order. It uses bitwise logic to extract one bit at a time.
This example builds a string backwards to ensure the digits are displayed in the correct order. It uses bitwise logic to extract one bit at a time.
<lang axe>Lbl BIN
<syntaxhighlight lang=axe>Lbl BIN
.Axe supports 16-bit integers, so 16 digits are enough
.Axe supports 16-bit integers, so 16 digits are enough
L₁+16→P
L₁+16→P
Line 1,146: Line 1,146:
End
End
Disp P,i
Disp P,i
Return</lang>
Return</syntaxhighlight>


=={{header|BaCon}}==
=={{header|BaCon}}==
<lang freebasic>' Binary digits
<syntaxhighlight lang=freebasic>' Binary digits
OPTION MEMTYPE int
OPTION MEMTYPE int
INPUT n$
INPUT n$
Line 1,156: Line 1,156:
ELSE
ELSE
PRINT CHOP$(BIN$(VAL(n$)), "0", 1)
PRINT CHOP$(BIN$(VAL(n$)), "0", 1)
ENDIF</lang>
ENDIF</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang ApplesoftBasic> 0 N = 5: GOSUB 1:N = 50: GOSUB 1:N = 9000: GOSUB 1: END
<syntaxhighlight lang=ApplesoftBasic> 0 N = 5: GOSUB 1:N = 50: GOSUB 1:N = 9000: GOSUB 1: END
1 LET N2 = ABS ( INT (N))
1 LET N2 = ABS ( INT (N))
2 LET B$ = ""
2 LET B$ = ""
Line 1,170: Line 1,170:
7 NEXT N1
7 NEXT N1
8 PRINT B$
8 PRINT B$
9 RETURN</lang>
9 RETURN</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 1,178: Line 1,178:


==={{header|BASIC256}}===
==={{header|BASIC256}}===
<lang basic256>
<syntaxhighlight lang=basic256>
# DecToBin.bas
# DecToBin.bas
# BASIC256 1.1.4.0
# BASIC256 1.1.4.0
Line 1,189: Line 1,189:
print a[i] + chr(9) + toRadix(a[i],2) # radix (decimal, base2)
print a[i] + chr(9) + toRadix(a[i],2) # radix (decimal, base2)
next i
next i
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,198: Line 1,198:


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
<lang bbcbasic> FOR num% = 0 TO 16
<syntaxhighlight lang=bbcbasic> FOR num% = 0 TO 16
PRINT FN_tobase(num%, 2, 0)
PRINT FN_tobase(num%, 2, 0)
NEXT
NEXT
Line 1,213: Line 1,213:
M% -= 1
M% -= 1
UNTIL (N%=FALSE OR N%=TRUE) AND M%<=0
UNTIL (N%=FALSE OR N%=TRUE) AND M%<=0
=A$</lang>
=A$</syntaxhighlight>
The above is a generic "Convert to any base" program.
The above is a generic "Convert to any base" program.
Here is a faster "Convert to Binary" program:
Here is a faster "Convert to Binary" program:
<lang bbcbasic>PRINT FNbinary(5)
<syntaxhighlight lang=bbcbasic>PRINT FNbinary(5)
PRINT FNbinary(50)
PRINT FNbinary(50)
PRINT FNbinary(9000)
PRINT FNbinary(9000)
Line 1,227: Line 1,227:
N% = N% >>> 1 : REM BBC Basic prior to V5 can use N% = N% DIV 2
N% = N% >>> 1 : REM BBC Basic prior to V5 can use N% = N% DIV 2
UNTIL N% = 0
UNTIL N% = 0
=A$</lang>
=A$</syntaxhighlight>


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
Line 1,234: Line 1,234:
Note the <tt>FOR N1 =</tt> ... <tt>TO 0 STEP 0</tt> idiom; the zero step means that the variable is not modified by BASIC, so it's up to the code inside the loop to eventually set <tt>N1</tt> to 0 so that the loop terminates – like a C <tt>for</tt> loop with an empty third clause. After the initialization, it's essentially a "while N1 is not 0" loop, but Commodore BASIC originally didn't have <b>while</b> loops (<tt>DO WHILE</tt> ... <tt>LOOP</tt> was added in BASIC 3.5). The alternative would be a <tt>GOTO</tt>, but the <tt>FOR</tt> loop lends more structure.
Note the <tt>FOR N1 =</tt> ... <tt>TO 0 STEP 0</tt> idiom; the zero step means that the variable is not modified by BASIC, so it's up to the code inside the loop to eventually set <tt>N1</tt> to 0 so that the loop terminates – like a C <tt>for</tt> loop with an empty third clause. After the initialization, it's essentially a "while N1 is not 0" loop, but Commodore BASIC originally didn't have <b>while</b> loops (<tt>DO WHILE</tt> ... <tt>LOOP</tt> was added in BASIC 3.5). The alternative would be a <tt>GOTO</tt>, but the <tt>FOR</tt> loop lends more structure.


<lang gwbasic>10 READ N
<syntaxhighlight lang=gwbasic>10 READ N
20 IF N < 0 THEN 70
20 IF N < 0 THEN 70
30 GOSUB 100
30 GOSUB 100
Line 1,247: Line 1,247:
130 : N1 = INT(N1/2)
130 : N1 = INT(N1/2)
140 NEXT N1
140 NEXT N1
150 RETURN</lang>
150 RETURN</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,257: Line 1,257:


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>10 PRINT BIN$(50)
<syntaxhighlight lang=IS-BASIC>10 PRINT BIN$(50)
100 DEF BIN$(N)
100 DEF BIN$(N)
110 LET N=ABS(INT(N)):LET B$=""
110 LET N=ABS(INT(N)):LET B$=""
Line 1,264: Line 1,264:
150 LOOP WHILE N>0
150 LOOP WHILE N>0
160 LET BIN$=B$
160 LET BIN$=B$
170 END DEF</lang>
170 END DEF</syntaxhighlight>


==={{header|QBasic}}===
==={{header|QBasic}}===
<lang QBasic>FUNCTION BIN$ (N)
<syntaxhighlight lang=QBasic>FUNCTION BIN$ (N)
N = ABS(INT(N))
N = ABS(INT(N))
B$ = ""
B$ = ""
Line 1,280: Line 1,280:
PRINT USING fmt$; 5; BIN$(5)
PRINT USING fmt$; 5; BIN$(5)
PRINT USING fmt$; 50; BIN$(50)
PRINT USING fmt$; 50; BIN$(50)
PRINT USING fmt$; 9000; BIN$(9000)</lang>
PRINT USING fmt$; 9000; BIN$(9000)</syntaxhighlight>


==={{header|Tiny BASIC}}===
==={{header|Tiny BASIC}}===


This turns into a horrible mess because of the lack of string concatenation in print statements, and the necessity of suppressing leading zeroes.
This turns into a horrible mess because of the lack of string concatenation in print statements, and the necessity of suppressing leading zeroes.
<lang tinybasic}}>REM variables:
<syntaxhighlight lang=tinybasic}}>REM variables:
REM A-O: binary digits with A least significant and N most significant
REM A-O: binary digits with A least significant and N most significant
REM X: number whose binary expansion we want
REM X: number whose binary expansion we want
Line 1,368: Line 1,368:


999 PRINT 0 REM zero is the one time we DO want to print a leading zero
999 PRINT 0 REM zero is the one time we DO want to print a leading zero
END</lang>
END</syntaxhighlight>


==={{header|True BASIC}}===
==={{header|True BASIC}}===
<lang qbasic>FUNCTION BIN$ (N)
<syntaxhighlight lang=qbasic>FUNCTION BIN$ (N)
LET N = ABS(INT(N))
LET N = ABS(INT(N))
LET B$ = ""
LET B$ = ""
Line 1,389: Line 1,389:
PRINT USING "####": 9000;
PRINT USING "####": 9000;
PRINT " -> "; BIN$(9000)
PRINT " -> "; BIN$(9000)
END</lang>
END</syntaxhighlight>


=={{header|Bash}}==
=={{header|Bash}}==
<lang BASH>
<syntaxhighlight lang=BASH>
function to_binary () {
function to_binary () {
if [ $1 -ge 0 ]
if [ $1 -ge 0 ]
Line 1,416: Line 1,416:
echo $number " :> " $(to_binary $number)
echo $number " :> " $(to_binary $number)
done
done
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,426: Line 1,426:
=={{header|Batch File}}==
=={{header|Batch File}}==
This num2bin.bat file handles non-negative input as per the requirements with no leading zeros in the output. Batch only supports signed integers. This script also handles negative values by printing the appropriate two's complement notation.
This num2bin.bat file handles non-negative input as per the requirements with no leading zeros in the output. Batch only supports signed integers. This script also handles negative values by printing the appropriate two's complement notation.
<lang dos>@echo off
<syntaxhighlight lang=dos>@echo off
:num2bin IntVal [RtnVar]
:num2bin IntVal [RtnVar]
setlocal enableDelayedExpansion
setlocal enableDelayedExpansion
Line 1,439: Line 1,439:
if "%~2" neq "" (set %~2=%rtn%) else echo %rtn%
if "%~2" neq "" (set %~2=%rtn%) else echo %rtn%
)
)
exit /b</lang>
exit /b</syntaxhighlight>


=={{header|bc}}==
=={{header|bc}}==
{{trans|dc}}
{{trans|dc}}
<lang bc>obase = 2
<syntaxhighlight lang=bc>obase = 2
5
5
50
50
9000
9000
quit</lang>
quit</syntaxhighlight>


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


let writebin(x) be
let writebin(x) be
Line 1,465: Line 1,465:
writebin(50)
writebin(50)
writebin(9000)
writebin(9000)
$)</lang>
$)</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 1,472: Line 1,472:


=={{header|Beads}}==
=={{header|Beads}}==
<lang Beads>beads 1 program 'Binary Digits'
<syntaxhighlight lang=Beads>beads 1 program 'Binary Digits'
calc main_init
calc main_init
loop across:[5, 50, 9000] val:v
loop across:[5, 50, 9000] val:v
log to_str(v, base:2)</lang>
log to_str(v, base:2)</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 1,484: Line 1,484:
=={{header|Befunge}}==
=={{header|Befunge}}==
Reads the number to convert from standard input.
Reads the number to convert from standard input.
<lang befunge>&>0\55+\:2%68>*#<+#8\#62#%/#2:_$>:#,_$@</lang>
<syntaxhighlight lang=befunge>&>0\55+\:2%68>*#<+#8\#62#%/#2:_$>:#,_$@</syntaxhighlight>
{{out}}
{{out}}
<pre>9000
<pre>9000
Line 1,492: Line 1,492:


A BQNcrate idiom which returns the digits as a boolean array.
A BQNcrate idiom which returns the digits as a boolean array.
<lang bqn>Bin ← 2{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}
<syntaxhighlight lang=bqn>Bin ← 2{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}


Bin¨5‿50‿9000</lang><lang>⟨ ⟨ 1 0 1 ⟩ ⟨ 1 1 0 0 1 0 ⟩ ⟨ 1 0 0 0 1 1 0 0 1 0 1 0 0 0 ⟩ ⟩</lang>
Bin¨5‿50‿9000</syntaxhighlight><syntaxhighlight lang=text>⟨ ⟨ 1 0 1 ⟩ ⟨ 1 1 0 0 1 0 ⟩ ⟨ 1 0 0 0 1 1 0 0 1 0 1 0 0 0 ⟩ ⟩</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat> ( dec2bin
<syntaxhighlight lang=bracmat> ( dec2bin
= bit bits
= bit bits
. :?bits
. :?bits
Line 1,513: Line 1,513:
& put$(str$(!dec ":\n" dec2bin$!dec \n\n))
& put$(str$(!dec ":\n" dec2bin$!dec \n\n))
)
)
;</lang>
;</syntaxhighlight>
{{out}}
{{out}}
<pre>0:
<pre>0:
Line 1,534: Line 1,534:
This is almost an exact duplicate of [[Count in octal#Brainf***]]. It outputs binary numbers until it is forced to terminate or the counter overflows to 0.
This is almost an exact duplicate of [[Count in octal#Brainf***]]. It outputs binary numbers until it is forced to terminate or the counter overflows to 0.


<lang bf>+[ Start with n=1 to kick off the loop
<syntaxhighlight lang=bf>+[ Start with n=1 to kick off the loop
[>>++<< Set up {n 0 2} for divmod magic
[>>++<< Set up {n 0 2} for divmod magic
[->+>- Then
[->+>- Then
Line 1,550: Line 1,550:
<[[-]<] Zero the tape for the next iteration
<[[-]<] Zero the tape for the next iteration
++++++++++. Print a newline
++++++++++. Print a newline
[-]<+] Zero it then increment n and go again</lang>
[-]<+] Zero it then increment n and go again</syntaxhighlight>


=={{header|Burlesque}}==
=={{header|Burlesque}}==
<lang burlesque>
<syntaxhighlight lang=burlesque>
blsq ) {5 50 9000}{2B!}m[uN
blsq ) {5 50 9000}{2B!}m[uN
101
101
110010
110010
10001100101000
10001100101000
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
===With bit level operations===
===With bit level operations===
<lang C>#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings
<syntaxhighlight lang=C>#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings
#define _CRT_NONSTDC_NO_DEPRECATE // enable old-gold POSIX names in MSVS
#define _CRT_NONSTDC_NO_DEPRECATE // enable old-gold POSIX names in MSVS


Line 1,668: Line 1,668:
return EXIT_SUCCESS;
return EXIT_SUCCESS;
}
}
</syntaxhighlight>
</lang>
{{output}}
{{output}}
<pre>itoa: 5 decimal = 101 binary
<pre>itoa: 5 decimal = 101 binary
Line 1,682: Line 1,682:
===With malloc and log10===
===With malloc and log10===
Converts int to a string.
Converts int to a string.
<lang c>#include <math.h>
<syntaxhighlight lang=c>#include <math.h>
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
Line 1,708: Line 1,708:
ret[bits] = '\0';
ret[bits] = '\0';
return ret;
return ret;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,733: Line 1,733:


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang=csharp>using System;


class Program
class Program
Line 1,744: Line 1,744:
}
}
}
}
}</lang>
}</syntaxhighlight>
Another version using dotnet 5<lang csharp dotnet 5.0>using System;
Another version using dotnet 5<syntaxhighlight lang=csharp dotnet 5.0>using System;
using System.Text;
using System.Text;


Line 1,758: Line 1,758:
Console.WriteLine(ToBinary(5));
Console.WriteLine(ToBinary(5));
Console.WriteLine(ToBinary(50));
Console.WriteLine(ToBinary(50));
Console.WriteLine(ToBinary(9000));</lang>
Console.WriteLine(ToBinary(9000));</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,767: Line 1,767:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <bitset>
<syntaxhighlight lang=cpp>#include <bitset>
#include <iostream>
#include <iostream>
#include <limits>
#include <limits>
Line 1,789: Line 1,789:
print_bin(9000);
print_bin(9000);
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,798: Line 1,798:
</pre>
</pre>
Shorter version using bitset
Shorter version using bitset
<lang cpp>#include <iostream>
<syntaxhighlight lang=cpp>#include <iostream>
#include <bitset>
#include <bitset>
void printBits(int n) { // Use int like most programming languages.
void printBits(int n) { // Use int like most programming languages.
Line 1,811: Line 1,811:
printBits(50);
printBits(50);
printBits(9000);
printBits(9000);
} // for testing with n=0 printBits<32>(0);</lang>
} // for testing with n=0 printBits<32>(0);</syntaxhighlight>
Using >> operator. (1st example is 2.75x longer. Matter of taste.)
Using >> operator. (1st example is 2.75x longer. Matter of taste.)
<lang cpp>#include <iostream>
<syntaxhighlight lang=cpp>#include <iostream>
int main(int argc, char* argv[]) {
int main(int argc, char* argv[]) {
unsigned int in[] = {5, 50, 9000}; // Use int like most programming languages
unsigned int in[] = {5, 50, 9000}; // Use int like most programming languages
Line 1,821: Line 1,821:
std::cout << ('0' + b & 1) << (!at ? "\n": ""); // '0' or '1'. Add EOL if last bit of num
std::cout << ('0' + b & 1) << (!at ? "\n": ""); // '0' or '1'. Add EOL if last bit of num
}
}
</syntaxhighlight>
</lang>
To be fair comparison with languages that doesn't declare a function like C++ main(). 3.14x shorter than 1st example.
To be fair comparison with languages that doesn't declare a function like C++ main(). 3.14x shorter than 1st example.
<lang cpp>#include <iostream>
<syntaxhighlight lang=cpp>#include <iostream>
int main(int argc, char* argv[]) { // Usage: program.exe 5 50 9000
int main(int argc, char* argv[]) { // Usage: program.exe 5 50 9000
for (int i = 1; i < argc; i++) // argv[0] is program name
for (int i = 1; i < argc; i++) // argv[0] is program name
Line 1,830: Line 1,830:
std::cout << ('0' + b & 1) << (!at ? "\n": ""); // '0' or '1'. Add EOL if last bit of num
std::cout << ('0' + b & 1) << (!at ? "\n": ""); // '0' or '1'. Add EOL if last bit of num
}
}
</syntaxhighlight>
</lang>
Using bitwise operations with recursion.
Using bitwise operations with recursion.
<lang cpp>
<syntaxhighlight lang=cpp>
#include <iostream>
#include <iostream>


Line 1,844: Line 1,844:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,853: Line 1,853:


=={{header|Ceylon}}==
=={{header|Ceylon}}==
<lang ceylon> shared void run() {
<syntaxhighlight lang=ceylon> shared void run() {
void printBinary(Integer integer) =>
void printBinary(Integer integer) =>
Line 1,861: Line 1,861:
printBinary(50);
printBinary(50);
printBinary(9k);
printBinary(9k);
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(Integer/toBinaryString 5)
<syntaxhighlight lang=clojure>(Integer/toBinaryString 5)
(Integer/toBinaryString 50)
(Integer/toBinaryString 50)
(Integer/toBinaryString 9000)</lang>
(Integer/toBinaryString 9000)</syntaxhighlight>


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>binary = proc (n: int) returns (string)
<syntaxhighlight lang=clu>binary = proc (n: int) returns (string)
bin: string := ""
bin: string := ""
while n > 0 do
while n > 0 do
Line 1,885: Line 1,885:
stream$putl(po, int$unparse(test) || " -> " || binary(test))
stream$putl(po, int$unparse(test) || " -> " || binary(test))
end
end
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>5 -> 101
<pre>5 -> 101
Line 1,892: Line 1,892:


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang COBOL> IDENTIFICATION DIVISION.
<syntaxhighlight lang=COBOL> IDENTIFICATION DIVISION.
PROGRAM-ID. SAMPLE.
PROGRAM-ID. SAMPLE.


Line 1,918: Line 1,918:
display binary_number
display binary_number
stop run.
stop run.
</syntaxhighlight>
</lang>
Free-form, using a reference modifier to index into binary-number.
Free-form, using a reference modifier to index into binary-number.
<lang cobol>IDENTIFICATION DIVISION.
<syntaxhighlight lang=cobol>IDENTIFICATION DIVISION.
PROGRAM-ID. binary-conversion.
PROGRAM-ID. binary-conversion.


Line 1,946: Line 1,946:
end-perform.
end-perform.
display binary-number.
display binary-number.
stop run.</lang>
stop run.</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>binary = (n) ->
<syntaxhighlight lang=coffeescript>binary = (n) ->
new Number(n).toString(2)
new Number(n).toString(2)
console.log binary n for n in [5, 50, 9000]</lang>
console.log binary n for n in [5, 50, 9000]</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Just print the number with "~b":
Just print the number with "~b":
<lang lisp>(format t "~b" 5)
<syntaxhighlight lang=lisp>(format t "~b" 5)


; or
; or


(write 5 :base 2)</lang>
(write 5 :base 2)</syntaxhighlight>


=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
BlackBox Component Builder
BlackBox Component Builder
<lang oberon2>
<syntaxhighlight lang=oberon2>
MODULE BinaryDigits;
MODULE BinaryDigits;
IMPORT StdLog,Strings;
IMPORT StdLog,Strings;
Line 1,980: Line 1,980:
END Do;
END Do;
END BinaryDigits.
END BinaryDigits.
</syntaxhighlight>
</lang>
Execute: ^Q BinaryDigits.Do <br/>
Execute: ^Q BinaryDigits.Do <br/>
{{out}}
{{out}}
Line 1,989: Line 1,989:


=={{header|Cowgol}}==
=={{header|Cowgol}}==
<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang=cowgol>include "cowgol.coh";


sub print_binary(n: uint32) is
sub print_binary(n: uint32) is
Line 2,008: Line 2,008:
print_binary(5);
print_binary(5);
print_binary(50);
print_binary(50);
print_binary(9000);</lang>
print_binary(9000);</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 2,017: Line 2,017:
{{trans|Ruby}}
{{trans|Ruby}}
Using an array
Using an array
<lang ruby>[5,50,9000].each do |n|
<syntaxhighlight lang=ruby>[5,50,9000].each do |n|
puts "%b" % n
puts "%b" % n
end</lang>
end</syntaxhighlight>
Using a tuple
Using a tuple
<lang ruby>{5,50,9000}.each { |n| puts n.to_s(2) }</lang>
<syntaxhighlight lang=ruby>{5,50,9000}.each { |n| puts n.to_s(2) }</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 2,028: Line 2,028:


=={{header|D}}==
=={{header|D}}==
<lang d>void main() {
<syntaxhighlight lang=d>void main() {
import std.stdio;
import std.stdio;


foreach (immutable i; 0 .. 16)
foreach (immutable i; 0 .. 16)
writefln("%b", i);
writefln("%b", i);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>0
<pre>0
Line 2,053: Line 2,053:


=={{header|Dart}}==
=={{header|Dart}}==
<lang dart>String binary(int n) {
<syntaxhighlight lang=dart>String binary(int n) {
if(n<0)
if(n<0)
throw new IllegalArgumentException("negative numbers require 2s complement");
throw new IllegalArgumentException("negative numbers require 2s complement");
Line 2,077: Line 2,077:
// fails due to precision limit
// fails due to precision limit
print(binary(0x123456789abcdef));
print(binary(0x123456789abcdef));
}</lang>
}</syntaxhighlight>


=={{header|dc}}==
=={{header|dc}}==
<lang dc>2o 5p 50p 9000p</lang>
<syntaxhighlight lang=dc>2o 5p 50p 9000p</syntaxhighlight>


{{out}}
{{out}}
Line 2,088: Line 2,088:


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>
<syntaxhighlight lang=Delphi>
program BinaryDigit;
program BinaryDigit;
{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 2,107: Line 2,107:
writeln(' 50: ',IntToBinStr(50));
writeln(' 50: ',IntToBinStr(50));
writeln('9000: '+IntToBinStr(9000));
writeln('9000: '+IntToBinStr(9000));
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,119: Line 2,119:
A default <code>ToString</code> method of type <code>Integer</code> is overriden and returns a binary representation of a number:
A default <code>ToString</code> method of type <code>Integer</code> is overriden and returns a binary representation of a number:


<lang dyalect>func Integer.ToString() {
<syntaxhighlight lang=dyalect>func Integer.ToString() {
var s = ""
var s = ""
for x in 31^-1..0 {
for x in 31^-1..0 {
Line 2,131: Line 2,131:
}
}
print("5 == \(5), 50 = \(50), 1000 = \(9000)")</lang>
print("5 == \(5), 50 = \(50), 1000 = \(9000)")</syntaxhighlight>


{{out}}
{{out}}
Line 2,139: Line 2,139:
=={{header|EasyLang}}==
=={{header|EasyLang}}==


<lang>func to2 n . r$ .
<syntaxhighlight lang=text>func to2 n . r$ .
if n > 0
if n > 0
call to2 n div 2 r$
call to2 n div 2 r$
Line 2,161: Line 2,161:
call pr2 5
call pr2 5
call pr2 50
call pr2 50
call pr2 9000</lang>
call pr2 9000</syntaxhighlight>


<pre>
<pre>
Line 2,170: Line 2,170:


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang=scheme>
;; primitive : (number->string number [base]) - default base = 10
;; primitive : (number->string number [base]) - default base = 10


Line 2,180: Line 2,180:
110010
110010
10001100101000
10001100101000
</syntaxhighlight>
</lang>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 5.0 :
<lang elena>import system'routines;
<syntaxhighlight lang=elena>import system'routines;
import extensions;
import extensions;


Line 2,193: Line 2,193:
console.printLine(n.toString(2))
console.printLine(n.toString(2))
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,203: Line 2,203:
=={{header|Elixir}}==
=={{header|Elixir}}==
Use <code>Integer.to_string</code> with a base of 2:
Use <code>Integer.to_string</code> with a base of 2:
<lang Elixir>
<syntaxhighlight lang=Elixir>
IO.puts Integer.to_string(5,2)
IO.puts Integer.to_string(5,2)
</syntaxhighlight>
</lang>
Or, using the pipe operator:
Or, using the pipe operator:
<lang Elixir>
<syntaxhighlight lang=Elixir>
5 |> Integer.to_string(2) |> IO.puts
5 |> Integer.to_string(2) |> IO.puts
</syntaxhighlight>
</lang>
<lang Elixir>
<syntaxhighlight lang=Elixir>
[5,50,9000] |> Enum.each(fn n -> IO.puts Integer.to_string(n,2) end)
[5,50,9000] |> Enum.each(fn n -> IO.puts Integer.to_string(n,2) end)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,222: Line 2,222:


=={{header|Epoxy}}==
=={{header|Epoxy}}==
<lang epoxy>fn bin(a,b:true)
<syntaxhighlight lang=epoxy>fn bin(a,b:true)
var c:""
var c:""
while a>0 do
while a>0 do
Line 2,237: Line 2,237:
iter Value of List do
iter Value of List do
log(Value+": "+bin(Value,false))
log(Value+": "+bin(Value,false))
cls</lang>
cls</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,246: Line 2,246:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>lists:map( fun(N) -> io:fwrite("~.2B~n", [N]) end, [5, 50, 9000]). </lang>
<syntaxhighlight lang=erlang>lists:map( fun(N) -> io:fwrite("~.2B~n", [N]) end, [5, 50, 9000]). </syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 2,253: Line 2,253:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>function toBinary(integer i)
<syntaxhighlight lang=euphoria>function toBinary(integer i)
sequence s
sequence s
s = {}
s = {}
Line 2,265: Line 2,265:
puts(1, toBinary(5) & '\n')
puts(1, toBinary(5) & '\n')
puts(1, toBinary(50) & '\n')
puts(1, toBinary(50) & '\n')
puts(1, toBinary(9000) & '\n')</lang>
puts(1, toBinary(9000) & '\n')</syntaxhighlight>


=== Functional/Recursive ===
=== Functional/Recursive ===
<lang euphoria>include std/math.e
<syntaxhighlight lang=euphoria>include std/math.e
include std/convert.e
include std/convert.e


Line 2,283: Line 2,283:
printf(1, "%d\n", Bin(5))
printf(1, "%d\n", Bin(5))
printf(1, "%d\n", Bin(50))
printf(1, "%d\n", Bin(50))
printf(1, "%d\n", Bin(9000))</lang>
printf(1, "%d\n", Bin(9000))</syntaxhighlight>


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
By translating C#'s approach, using imperative coding style (inflexible):
By translating C#'s approach, using imperative coding style (inflexible):
<lang FSharp>open System
<syntaxhighlight lang=FSharp>open System
for i in [5; 50; 9000] do printfn "%s" <| Convert.ToString (i, 2)</lang>
for i in [5; 50; 9000] do printfn "%s" <| Convert.ToString (i, 2)</syntaxhighlight>


Alternatively, by creating a function <code>printBin</code> which prints in binary (more flexible):
Alternatively, by creating a function <code>printBin</code> which prints in binary (more flexible):
<lang FSharp>open System
<syntaxhighlight lang=FSharp>open System


// define the function
// define the function
Line 2,300: Line 2,300:
// use the function
// use the function
[5; 50; 9000]
[5; 50; 9000]
|> List.iter printBin</lang>
|> List.iter printBin</syntaxhighlight>


Or more idiomatic so that you can use it with any printf-style function and the <code>%a</code> format specifier (most flexible):
Or more idiomatic so that you can use it with any printf-style function and the <code>%a</code> format specifier (most flexible):


<lang FSharp>open System
<syntaxhighlight lang=FSharp>open System
open System.IO
open System.IO


Line 2,313: Line 2,313:
// use it with printfn with %a
// use it with printfn with %a
[5; 50; 9000]
[5; 50; 9000]
|> List.iter (printfn "binary: %a" bin)</lang>
|> List.iter (printfn "binary: %a" bin)</syntaxhighlight>
Output (either version):
Output (either version):
<pre>
<pre>
Line 2,322: Line 2,322:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: io kernel math math.parser ;
<syntaxhighlight lang=factor>USING: io kernel math math.parser ;


5 >bin print
5 >bin print
50 >bin print
50 >bin print
9000 >bin print</lang>
9000 >bin print</syntaxhighlight>


=={{header|FALSE}}==
=={{header|FALSE}}==
<lang false>[0\10\[$1&'0+\2/$][]#%[$][,]#%]b:
<syntaxhighlight lang=false>[0\10\[$1&'0+\2/$][]#%[$][,]#%]b:


5 b;!
5 b;!
50 b;!
50 b;!
9000 b;!</lang>
9000 b;!</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 2,340: Line 2,340:


=={{header|FBSL}}==
=={{header|FBSL}}==
<lang fbsl>#AppType Console
<syntaxhighlight lang=fbsl>#AppType Console
function Bin(byval n as integer, byval s as string = "") as string
function Bin(byval n as integer, byval s as string = "") as string
if n > 0 then return Bin(n \ 2, (n mod 2) & s)
if n > 0 then return Bin(n \ 2, (n mod 2) & s)
Line 2,352: Line 2,352:


pause
pause
</syntaxhighlight>
</lang>


=={{header|FOCAL}}==
=={{header|FOCAL}}==
<lang FOCAL>01.10 S A=5;D 2
<syntaxhighlight lang=FOCAL>01.10 S A=5;D 2
01.20 S A=50;D 2
01.20 S A=50;D 2
01.30 S A=9000;D 2
01.30 S A=9000;D 2
Line 2,369: Line 2,369:
02.50 I (-BX)2.4;T !;R
02.50 I (-BX)2.4;T !;R
02.60 I (-BD(BX))2.7;T "0";R
02.60 I (-BD(BX))2.7;T "0";R
02.70 T "1"</lang>
02.70 T "1"</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 2,376: Line 2,376:


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>\ Forth uses a system variable 'BASE' for number conversion
<syntaxhighlight lang=forth>\ Forth uses a system variable 'BASE' for number conversion


\ HEX is a standard word to change the value of base to 16
\ HEX is a standard word to change the value of base to 16
Line 2,395: Line 2,395:
decimal
decimal


</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,407: Line 2,407:
=={{header|Fortran}}==
=={{header|Fortran}}==
Please find compilation instructions and the example run at the start of the FORTRAN90 source that follows. Thank you.
Please find compilation instructions and the example run at the start of the FORTRAN90 source that follows. Thank you.
<lang FORTRAN>
<syntaxhighlight lang=FORTRAN>
!-*- mode: compilation; default-directory: "/tmp/" -*-
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sun May 19 23:14:14
!Compilation started at Sun May 19 23:14:14
Line 2,465: Line 2,465:


end program bits
end program bits
</syntaxhighlight>
</lang>


=={{header|Free Pascal}}==
=={{header|Free Pascal}}==
As part of the RTL (run-time library) that is shipped with every FPC (Free Pascal compiler) distribution, the <tt>system</tt> unit contains the function <tt>binStr</tt>.
As part of the RTL (run-time library) that is shipped with every FPC (Free Pascal compiler) distribution, the <tt>system</tt> unit contains the function <tt>binStr</tt>.
The <tt>system</tt> unit is automatically included by ''every'' program and is guaranteed to work on every supported platform.
The <tt>system</tt> unit is automatically included by ''every'' program and is guaranteed to work on every supported platform.
<lang pascal>program binaryDigits(input, output, stdErr);
<syntaxhighlight lang=pascal>program binaryDigits(input, output, stdErr);
{$mode ISO}
{$mode ISO}


Line 2,492: Line 2,492:
writeLn(binaryNumber(50));
writeLn(binaryNumber(50));
writeLn(binaryNumber(9000));
writeLn(binaryNumber(9000));
end.</lang>
end.</syntaxhighlight>
Note, that the ISO compliant <tt>mod</tt> operation has to be used, which is ensured by the <tt>{$mode}</tt> directive in the second line.
Note, that the ISO compliant <tt>mod</tt> operation has to be used, which is ensured by the <tt>{$mode}</tt> directive in the second line.


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>
<syntaxhighlight lang=freebasic>
' FreeBASIC v1.05.0 win64
' FreeBASIC v1.05.0 win64
Dim As String fmt = "#### -> &"
Dim As String fmt = "#### -> &"
Line 2,506: Line 2,506:
Sleep
Sleep
End
End
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,517: Line 2,517:
=={{header|Frink}}==
=={{header|Frink}}==
The following all provide equivalent output. Input can be arbitrarily-large integers.
The following all provide equivalent output. Input can be arbitrarily-large integers.
<lang frink>
<syntaxhighlight lang=frink>
9000 -> binary
9000 -> binary
9000 -> base2
9000 -> base2
base2[9000]
base2[9000]
base[9000, 2]
base[9000, 2]
</syntaxhighlight>
</lang>


=={{header|FunL}}==
=={{header|FunL}}==
<lang funl>for n <- [5, 50, 9000, 9000000000]
<syntaxhighlight lang=funl>for n <- [5, 50, 9000, 9000000000]
println( n, bin(n) )</lang>
println( n, bin(n) )</syntaxhighlight>


{{out}}
{{out}}
Line 2,541: Line 2,541:
We produce the binary number as a 64-bit integer whose digits are all 0s and 1s - this is because Futhark does not have any way to print, nor strings for that matter.
We produce the binary number as a 64-bit integer whose digits are all 0s and 1s - this is because Futhark does not have any way to print, nor strings for that matter.


<lang Futhark>
<syntaxhighlight lang=Futhark>
fun main(x: i32): i64 =
fun main(x: i32): i64 =
loop (out = 0i64) = for i < 32 do
loop (out = 0i64) = for i < 32 do
Line 2,548: Line 2,548:
in out
in out
in out
in out
</syntaxhighlight>
</lang>




=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
The decimal to binary conversion can be handled with a simple function.
The decimal to binary conversion can be handled with a simple function.
<lang futurebasic>
<syntaxhighlight lang=futurebasic>
include "NSLog.incl"
include "NSLog.incl"


Line 2,570: Line 2,570:


HandleEvents
HandleEvents
</syntaxhighlight>
</lang>
{{output}}
{{output}}
<pre>
<pre>
Line 2,581: Line 2,581:
=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=03e84768e6ee2af9b7664efa04fa6da8 Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=03e84768e6ee2af9b7664efa04fa6da8 Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang=gambas>Public Sub Main()
Dim siBin As Short[] = [5, 50, 9000]
Dim siBin As Short[] = [5, 50, 9000]
Dim siCount As Short
Dim siCount As Short
Line 2,589: Line 2,589:
Next
Next


End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,598: Line 2,598:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang=go>package main


import (
import (
Line 2,608: Line 2,608:
fmt.Printf("%b\n", i)
fmt.Printf("%b\n", i)
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,631: Line 2,631:
=={{header|Groovy}}==
=={{header|Groovy}}==
Solutions:
Solutions:
<lang groovy>print '''
<syntaxhighlight lang=groovy>print '''
n binary
n binary
----- ---------------
----- ---------------
Line 2,637: Line 2,637:
[5, 50, 9000].each {
[5, 50, 9000].each {
printf('%5d %15s\n', it, Integer.toBinaryString(it))
printf('%5d %15s\n', it, Integer.toBinaryString(it))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> n binary
<pre> n binary
Line 2,646: Line 2,646:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Data.List
<syntaxhighlight lang=haskell>import Data.List
import Numeric
import Numeric
import Text.Printf
import Text.Printf
Line 2,669: Line 2,669:
main = do
main = do
putStrLn $ printf "%4s %14s %14s" "N" "toBin" "toBin1"
putStrLn $ printf "%4s %14s %14s" "N" "toBin" "toBin1"
mapM_ printToBin [5, 50, 9000]</lang>
mapM_ printToBin [5, 50, 9000]</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,681: Line 2,681:
and in terms of first and swap, we could also write this as:
and in terms of first and swap, we could also write this as:


<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 2,703: Line 2,703:
)
)
)
)
[5, 50, 9000]</lang>
[5, 50, 9000]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>5 -> 101
<pre>5 -> 101
Line 2,711: Line 2,711:
=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
There is no built-in way to output the bit string representation of an whole number in Icon and Unicon. There are generalized radix conversion routines in the Icon Programming Library that comes with every distribution. This procedure is a customized conversion routine that will populate and use a tunable cache as it goes.
There is no built-in way to output the bit string representation of an whole number in Icon and Unicon. There are generalized radix conversion routines in the Icon Programming Library that comes with every distribution. This procedure is a customized conversion routine that will populate and use a tunable cache as it goes.
<lang Icon>procedure main()
<syntaxhighlight lang=Icon>procedure main()
every i := 5 | 50 | 255 | 1285 | 9000 do
every i := 5 | 50 | 255 | 1285 | 9000 do
write(i," = ",binary(i))
write(i," = ",binary(i))
Line 2,733: Line 2,733:
}
}
return reverse(trim(b,"0")) # nothing extraneous
return reverse(trim(b,"0")) # nothing extraneous
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>5 = 101
<pre>5 = 101
Line 2,742: Line 2,742:


=={{header|Idris}}==
=={{header|Idris}}==
<lang Idris>module Main
<syntaxhighlight lang=Idris>module Main


binaryDigit : Integer -> Char
binaryDigit : Integer -> Char
Line 2,760: Line 2,760:
putStrLn (binaryString 50)
putStrLn (binaryString 50)
putStrLn (binaryString 9000)
putStrLn (binaryString 9000)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,770: Line 2,770:


=={{header|J}}==
=={{header|J}}==
<lang j> tobin=: -.&' '@":@#:
<syntaxhighlight lang=j> tobin=: -.&' '@":@#:
tobin 5
tobin 5
101
101
Line 2,776: Line 2,776:
110010
110010
tobin 9000
tobin 9000
10001100101000</lang>
10001100101000</syntaxhighlight>
Algorithm: Remove spaces from the character list which results from formatting the binary list which represents the numeric argument.
Algorithm: Remove spaces from the character list which results from formatting the binary list which represents the numeric argument.


Line 2,782: Line 2,782:


=={{header|Java}}==
=={{header|Java}}==
<lang java>public class Main {
<syntaxhighlight lang=java>public class Main {
public static void main(String[] args) {
public static void main(String[] args) {
System.out.println(Integer.toBinaryString(5));
System.out.println(Integer.toBinaryString(5));
Line 2,788: Line 2,788:
System.out.println(Integer.toBinaryString(9000));
System.out.println(Integer.toBinaryString(9000));
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 2,796: Line 2,796:
=={{header|JavaScript}}==
=={{header|JavaScript}}==
===ES5===
===ES5===
<lang javascript>function toBinary(number) {
<syntaxhighlight lang=javascript>function toBinary(number) {
return new Number(number)
return new Number(number)
.toString(2);
.toString(2);
Line 2,804: Line 2,804:
// alert() in a browser, wscript.echo in WSH, etc.
// alert() in a browser, wscript.echo in WSH, etc.
print(toBinary(demoValues[i]));
print(toBinary(demoValues[i]));
}</lang>
}</syntaxhighlight>


===ES6===
===ES6===
The simplest showBinary (or showIntAtBase), using default digit characters, would use JavaScript's standard String.toString(base):
The simplest showBinary (or showIntAtBase), using default digit characters, would use JavaScript's standard String.toString(base):


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


Line 2,832: Line 2,832:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>5 -> 101
<pre>5 -> 101
Line 2,840: Line 2,840:
Or, if we need more flexibility with the set of digits used, we can write a version of showIntAtBase which takes a more specific Int -> Char function as as an argument. This one is a rough translation of Haskell's Numeric.showIntAtBase:
Or, if we need more flexibility with the set of digits used, we can write a version of showIntAtBase which takes a more specific Int -> Char function as as an argument. This one is a rough translation of Haskell's Numeric.showIntAtBase:


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


Line 2,895: Line 2,895:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>5 -> 一〇一
<pre>5 -> 一〇一
Line 2,902: Line 2,902:


=={{header|Joy}}==
=={{header|Joy}}==
<lang joy>HIDE
<syntaxhighlight lang=joy>HIDE
_ == [null] [pop] [2 div swap] [48 + putch] linrec
_ == [null] [pop] [2 div swap] [48 + putch] linrec
IN
IN
int2bin == [null] [48 + putch] [_] ifte '\n putch
int2bin == [null] [48 + putch] [_] ifte '\n putch
END</lang>
END</syntaxhighlight>
Using int2bin:
Using int2bin:
<lang joy>0 setautoput
<syntaxhighlight lang=joy>0 setautoput
0 int2bin
0 int2bin
5 int2bin
5 int2bin
50 int2bin
50 int2bin
9000 int2bin.</lang>
9000 int2bin.</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
<lang jq>def binary_digits:
<syntaxhighlight lang=jq>def binary_digits:
[ recurse( ./2 | floor; . > 0) % 2 ] | reverse | join("") ;
[ recurse( ./2 | floor; . > 0) % 2 ] | reverse | join("") ;


# The task:
# The task:
(5, 50, 9000) | binary_digits</lang>
(5, 50, 9000) | binary_digits</syntaxhighlight>
{{Out}}
{{Out}}
$ jq -n -r -f Binary_digits.jq
$ jq -n -r -f Binary_digits.jq
Line 2,929: Line 2,929:
{{works with|Julia|1.0}}
{{works with|Julia|1.0}}


<lang julia>using Printf
<syntaxhighlight lang=julia>using Printf


for n in (0, 5, 50, 9000)
for n in (0, 5, 50, 9000)
Line 2,939: Line 2,939:
for n in (0, 5, 50, 9000)
for n in (0, 5, 50, 9000)
@printf("%6i → %s\n", n, string(n, base=2, pad=20))
@printf("%6i → %s\n", n, string(n, base=2, pad=20))
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 2,954: Line 2,954:


=={{header|K}}==
=={{header|K}}==
<lang k> tobin: ,/$2_vs
<syntaxhighlight lang=k> tobin: ,/$2_vs
tobin' 5 50 9000
tobin' 5 50 9000
("101"
("101"
"110010"
"110010"
"10001100101000")</lang>
"10001100101000")</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.5-2
<syntaxhighlight lang=scala>// version 1.0.5-2


fun main(args: Array<String>) {
fun main(args: Array<String>) {
val numbers = intArrayOf(5, 50, 9000)
val numbers = intArrayOf(5, 50, 9000)
for (number in numbers) println("%4d".format(number) + " -> " + Integer.toBinaryString(number))
for (number in numbers) println("%4d".format(number) + " -> " + Integer.toBinaryString(number))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,976: Line 2,976:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang=scheme>
{def dec2bin
{def dec2bin
{lambda {:dec}
{lambda {:dec}
Line 2,999: Line 2,999:
9000 -> 10001100101000
9000 -> 10001100101000


</syntaxhighlight>
</lang>


=={{header|Lang5}}==
=={{header|Lang5}}==
<lang lang5>'%b '__number_format set
<syntaxhighlight lang=lang5>'%b '__number_format set
[5 50 9000] [3 1] reshape .</lang>
[5 50 9000] [3 1] reshape .</syntaxhighlight>
{{out}}
{{out}}
<pre>[
<pre>[
Line 3,014: Line 3,014:


If one is simple printing the results and doesn't need to use them (e.g., assign them to any variables, etc.), this is very concise:
If one is simple printing the results and doesn't need to use them (e.g., assign them to any variables, etc.), this is very concise:
<lang lisp>
<syntaxhighlight lang=lisp>
(: io format '"~.2B~n~.2B~n~.2B~n" (list 5 50 9000))
(: io format '"~.2B~n~.2B~n~.2B~n" (list 5 50 9000))
</syntaxhighlight>
</lang>


If, however, you do need to get the results from a function, you can use <code>(: erlang integer_to_list ... )</code>. Here's a simple example that does the same thing as the previous code:
If, however, you do need to get the results from a function, you can use <code>(: erlang integer_to_list ... )</code>. Here's a simple example that does the same thing as the previous code:
<lang lisp>
<syntaxhighlight lang=lisp>
(: lists foreach
(: lists foreach
(lambda (x)
(lambda (x)
Line 3,026: Line 3,026:
(list (: erlang integer_to_list x 2))))
(list (: erlang integer_to_list x 2))))
(list 5 50 9000))
(list 5 50 9000))
</syntaxhighlight>
</lang>
{{out|note=for both examples}}
{{out|note=for both examples}}
<pre>
<pre>
Line 3,035: Line 3,035:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>for a = 0 to 16
<syntaxhighlight lang=lb>for a = 0 to 16
print a;"=";dec2bin$(a)
print a;"=";dec2bin$(a)
next
next
Line 3,050: Line 3,050:
wend
wend
end function
end function
</syntaxhighlight>
</lang>


=={{header|Little Man Computer}}==
=={{header|Little Man Computer}}==
Line 3,056: Line 3,056:


The maximum integer in LMC is 999, so 90000 in the task is here replaced by 900.
The maximum integer in LMC is 999, so 90000 in the task is here replaced by 900.
<lang Little Man Computer>
<syntaxhighlight lang=Little Man Computer>
// Little Man Computer, for Rosetta Code.
// Little Man Computer, for Rosetta Code.
// Read numbers from user and display them in binary.
// Read numbers from user and display them in binary.
Line 3,116: Line 3,116:
nrDigits DAT
nrDigits DAT
diff DAT
diff DAT
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,127: Line 3,127:
=={{header|LLVM}}==
=={{header|LLVM}}==
{{trans|C}}
{{trans|C}}
<lang llvm>; ModuleID = 'binary.c'
<syntaxhighlight lang=llvm>; ModuleID = 'binary.c'
; source_filename = "binary.c"
; source_filename = "binary.c"
; target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
; target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
Line 3,306: Line 3,306:
!0 = !{i32 1, !"wchar_size", i32 2}
!0 = !{i32 1, !"wchar_size", i32 2}
!1 = !{i32 7, !"PIC Level", i32 2}
!1 = !{i32 7, !"PIC Level", i32 2}
!2 = !{!"clang version 6.0.1 (tags/RELEASE_601/final)"}</lang>
!2 = !{!"clang version 6.0.1 (tags/RELEASE_601/final)"}</syntaxhighlight>
{{out}}
{{out}}
<pre>0
<pre>0
Line 3,330: Line 3,330:


=={{header|Locomotive Basic}}==
=={{header|Locomotive Basic}}==
<lang locobasic>10 PRINT BIN$(5)
<syntaxhighlight lang=locobasic>10 PRINT BIN$(5)
20 PRINT BIN$(50)
20 PRINT BIN$(50)
30 PRINT BIN$(9000)</lang>
30 PRINT BIN$(9000)</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 3,339: Line 3,339:


=={{header|LOLCODE}}==
=={{header|LOLCODE}}==
<lang LOLCODE>HAI 1.3
<syntaxhighlight lang=LOLCODE>HAI 1.3
HOW IZ I DECIMULBINUR YR DECIMUL
HOW IZ I DECIMULBINUR YR DECIMUL
I HAS A BINUR ITZ ""
I HAS A BINUR ITZ ""
Line 3,354: Line 3,354:
VISIBLE I IZ DECIMULBINUR YR 50 MKAY
VISIBLE I IZ DECIMULBINUR YR 50 MKAY
VISIBLE I IZ DECIMULBINUR YR 9000 MKAY
VISIBLE I IZ DECIMULBINUR YR 9000 MKAY
KTHXBYE</lang>
KTHXBYE</syntaxhighlight>


{{out}}
{{out}}
Line 3,363: Line 3,363:
=={{header|Lua}}==
=={{header|Lua}}==
===Lua - Iterative===
===Lua - Iterative===
<lang Lua>function dec2bin (n)
<syntaxhighlight lang=Lua>function dec2bin (n)
local bin = ""
local bin = ""
while n > 0 do
while n > 0 do
Line 3,374: Line 3,374:
print(dec2bin(5))
print(dec2bin(5))
print(dec2bin(50))
print(dec2bin(50))
print(dec2bin(9000))</lang>
print(dec2bin(9000))</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 3,381: Line 3,381:
===Lua - Recursive===
===Lua - Recursive===
{{works with|Lua|5.3+}}
{{works with|Lua|5.3+}}
<lang lua>function dec2bin(n, bin)
<syntaxhighlight lang=lua>function dec2bin(n, bin)
bin = (n&1) .. (bin or "") -- use n%2 instead of n&1 for Lua 5.1/5.2
bin = (n&1) .. (bin or "") -- use n%2 instead of n&1 for Lua 5.1/5.2
return n>1 and dec2bin(n//2, bin) or bin -- use math.floor(n/2) instead of n//2 for Lua 5.1/5.2
return n>1 and dec2bin(n//2, bin) or bin -- use math.floor(n/2) instead of n//2 for Lua 5.1/5.2
Line 3,388: Line 3,388:
print(dec2bin(5))
print(dec2bin(5))
print(dec2bin(50))
print(dec2bin(50))
print(dec2bin(9000))</lang>
print(dec2bin(9000))</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 3,395: Line 3,395:


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<lang M2000 Interpreter>
<syntaxhighlight lang=M2000 Interpreter>
Module Checkit {
Module Checkit {
Form 90, 40
Form 90, 40
Line 3,449: Line 3,449:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre style="height:30ex;overflow:scroll">
<pre style="height:30ex;overflow:scroll">
Line 3,469: Line 3,469:
matches the binary representation of the input, e.g. <code>BINARY.(5)</code> is <code>101</code>.
matches the binary representation of the input, e.g. <code>BINARY.(5)</code> is <code>101</code>.


<lang MAD> NORMAL MODE IS INTEGER
<syntaxhighlight lang=MAD> NORMAL MODE IS INTEGER
INTERNAL FUNCTION(NUM)
INTERNAL FUNCTION(NUM)
Line 3,489: Line 3,489:


VECTOR VALUES FMT = $I4,2H: ,I16*$
VECTOR VALUES FMT = $I4,2H: ,I16*$
END OF PROGRAM </lang>
END OF PROGRAM </syntaxhighlight>
{{out}}
{{out}}
<pre> 5: 101
<pre> 5: 101
Line 3,496: Line 3,496:


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>
<syntaxhighlight lang=Maple>
> convert( 50, 'binary' );
> convert( 50, 'binary' );
110010
110010
> convert( 9000, 'binary' );
> convert( 9000, 'binary' );
10001100101000
10001100101000
</syntaxhighlight>
</lang>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>StringJoin @@ ToString /@ IntegerDigits[50, 2] </lang>
<syntaxhighlight lang=Mathematica>StringJoin @@ ToString /@ IntegerDigits[50, 2] </syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<lang Matlab> dec2bin(5)
<syntaxhighlight lang=Matlab> dec2bin(5)
dec2bin(50)
dec2bin(50)
dec2bin(9000) </lang>
dec2bin(9000) </syntaxhighlight>
The output is a string containing ascii(48) (i.e. '0') and ascii(49) (i.e. '1').
The output is a string containing ascii(48) (i.e. '0') and ascii(49) (i.e. '1').


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>digits([arg]) := block(
<syntaxhighlight lang=maxima>digits([arg]) := block(
[n: first(arg), b: if length(arg) > 1 then second(arg) else 10, v: [ ], q],
[n: first(arg), b: if length(arg) > 1 then second(arg) else 10, v: [ ], q],
do (
do (
Line 3,524: Line 3,524:
/*
/*
10001100101000
10001100101000
*/</lang>
*/</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>
<syntaxhighlight lang=maxscript>
-- MAXScript: Output decimal numbers from 0 to 16 as Binary : N.H. 2019
-- MAXScript: Output decimal numbers from 0 to 16 as Binary : N.H. 2019
for k = 0 to 16 do
for k = 0 to 16 do
Line 3,550: Line 3,550:
print binString
print binString
)
)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
Output to MAXScript Listener:
Output to MAXScript Listener:
Line 3,574: Line 3,574:


=={{header|Mercury}}==
=={{header|Mercury}}==
<lang mercury>:- module binary_digits.
<syntaxhighlight lang=mercury>:- module binary_digits.
:- interface.
:- interface.


Line 3,590: Line 3,590:
print_binary_digits(N, !IO) :-
print_binary_digits(N, !IO) :-
io.write_string(int_to_base_string(N, 2), !IO),
io.write_string(int_to_base_string(N, 2), !IO),
io.nl(!IO).</lang>
io.nl(!IO).</syntaxhighlight>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>(2 over over mod 'div dip) :divmod2
<syntaxhighlight lang=min>(2 over over mod 'div dip) :divmod2


(
(
Line 3,603: Line 3,603:
) :bin
) :bin


(5 50 9000) (bin puts) foreach</lang>
(5 50 9000) (bin puts) foreach</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,613: Line 3,613:
=={{header|MiniScript}}==
=={{header|MiniScript}}==
=== Iterative ===
=== Iterative ===
<lang MiniScript>binary = function(n)
<syntaxhighlight lang=MiniScript>binary = function(n)
result = ""
result = ""
while n
while n
Line 3,626: Line 3,626:
print binary(50)
print binary(50)
print binary(9000)
print binary(9000)
print binary(0)</lang>
print binary(0)</syntaxhighlight>


=== Recursive ===
=== Recursive ===
<lang MiniScript>binary = function(n,result="")
<syntaxhighlight lang=MiniScript>binary = function(n,result="")
if n == 0 then
if n == 0 then
if result == "" then return "0" else return result
if result == "" then return "0" else return result
Line 3,640: Line 3,640:
print binary(50)
print binary(50)
print binary(9000)
print binary(9000)
print binary(0)</lang>
print binary(0)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,650: Line 3,650:


=={{header|mLite}}==
=={{header|mLite}}==
<lang sml>fun binary
<syntaxhighlight lang=sml>fun binary
(0, b) = implode ` map (fn x = if int x then chr (x + 48) else x) b
(0, b) = implode ` map (fn x = if int x then chr (x + 48) else x) b
| (n, b) = binary (n div 2, n mod 2 :: b)
| (n, b) = binary (n div 2, n mod 2 :: b)
| n = binary (n, [])
| n = binary (n, [])
;
;
</syntaxhighlight>
</lang>


==== from the REPL ====
==== from the REPL ====
Line 3,667: Line 3,667:


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE Binary;
<syntaxhighlight lang=modula2>MODULE Binary;
FROM FormatString IMPORT FormatString;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT Write,WriteLn,ReadChar;
FROM Terminal IMPORT Write,WriteLn,ReadChar;
Line 3,695: Line 3,695:


ReadChar
ReadChar
END Binary.</lang>
END Binary.</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>MODULE Binary EXPORTS Main;
<syntaxhighlight lang=modula3>MODULE Binary EXPORTS Main;


IMPORT IO, Fmt;
IMPORT IO, Fmt;
Line 3,708: Line 3,708:
num := 150;
num := 150;
IO.Put(Fmt.Int(num, 2) & "\n");
IO.Put(Fmt.Int(num, 2) & "\n");
END Binary.</lang>
END Binary.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,716: Line 3,716:


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang=NetRexx>/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 3,733: Line 3,733:
w_ = list.word(n_)
w_ = list.word(n_)
say w_.right(20)':' getBinaryDigits(w_)
say w_.right(20)':' getBinaryDigits(w_)
end n_</lang>
end n_</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,744: Line 3,744:
=={{header|NewLisp}}==
=={{header|NewLisp}}==


<lang NewLisp>
<syntaxhighlight lang=NewLisp>
;;; Using the built-in "bits" function
;;; Using the built-in "bits" function
;;; For integers up to 9,223,372,036,854,775,807
;;; For integers up to 9,223,372,036,854,775,807
Line 3,757: Line 3,757:
;;; Example
;;; Example
(println (big-bits 1234567890123456789012345678901234567890L))
(println (big-bits 1234567890123456789012345678901234567890L))
</syntaxhighlight>
</lang>
<pre>
<pre>
Output:
Output:
Line 3,781: Line 3,781:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>proc binDigits(x: BiggestInt, r: int): int =
<syntaxhighlight lang=nim>proc binDigits(x: BiggestInt, r: int): int =
## Calculates how many digits `x` has when each digit covers `r` bits.
## Calculates how many digits `x` has when each digit covers `r` bits.
result = 1
result = 1
Line 3,804: Line 3,804:


for i in 0..15:
for i in 0..15:
echo toBin(i)</lang>
echo toBin(i)</syntaxhighlight>
{{out}}
{{out}}
<pre>0
<pre>0
Line 3,824: Line 3,824:


===Version using strformat===
===Version using strformat===
<lang Nim>import strformat
<syntaxhighlight lang=Nim>import strformat


for n in 0..15:
for n in 0..15:
echo fmt"{n:b}"</lang>
echo fmt"{n:b}"</syntaxhighlight>


{{out}}
{{out}}
Line 3,848: Line 3,848:


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
<lang oberon2>
<syntaxhighlight lang=oberon2>
MODULE BinaryDigits;
MODULE BinaryDigits;
IMPORT Out;
IMPORT Out;
Line 3,866: Line 3,866:
OutBin(42); Out.Ln;
OutBin(42); Out.Ln;
END BinaryDigits.
END BinaryDigits.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,878: Line 3,878:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>class Binary {
<syntaxhighlight lang=objeck>class Binary {
function : Main(args : String[]) ~ Nil {
function : Main(args : String[]) ~ Nil {
5->ToBinaryString()->PrintLine();
5->ToBinaryString()->PrintLine();
Line 3,884: Line 3,884:
9000->ToBinaryString()->PrintLine();
9000->ToBinaryString()->PrintLine();
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,893: Line 3,893:


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let bin_of_int d =
<syntaxhighlight lang=ocaml>let bin_of_int d =
if d < 0 then invalid_arg "bin_of_int" else
if d < 0 then invalid_arg "bin_of_int" else
if d = 0 then "0" else
if d = 0 then "0" else
Line 3,904: Line 3,904:
let () =
let () =
let d = read_int () in
let d = read_int () in
Printf.printf "%8s\n" (bin_of_int d)</lang>
Printf.printf "%8s\n" (bin_of_int d)</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 3,925: Line 3,925:


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang=scheme>
(print (number->string 5 2))
(print (number->string 5 2))
(print (number->string 50 2))
(print (number->string 50 2))
(print (number->string 9000 2))
(print (number->string 9000 2))
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,939: Line 3,939:
=={{header|OxygenBasic}}==
=={{header|OxygenBasic}}==
The Assembly code uses block structures to minimise the use of labels.
The Assembly code uses block structures to minimise the use of labels.
<lang oxygenbasic>
<syntaxhighlight lang=oxygenbasic>


function BinaryBits(sys n) as string
function BinaryBits(sys n) as string
Line 3,983: Line 3,983:


print BinaryBits 0xaa 'result 10101010
print BinaryBits 0xaa 'result 10101010
</syntaxhighlight>
</lang>


=={{header|Panda}}==
=={{header|Panda}}==
<lang panda>0..15.radix:2 nl</lang>
<syntaxhighlight lang=panda>0..15.radix:2 nl</syntaxhighlight>
{{out}}
{{out}}
<pre>0
<pre>0
Line 4,006: Line 4,006:


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>bin(n:int)=concat(apply(s->Str(s),binary(n)))</lang>
<syntaxhighlight lang=parigp>bin(n:int)=concat(apply(s->Str(s),binary(n)))</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
{{works with|Free Pascal}}
{{works with|Free Pascal}}
FPC compiler Version 2.6 upwards.The obvious version.
FPC compiler Version 2.6 upwards.The obvious version.
<lang pascal>program IntToBinTest;
<syntaxhighlight lang=pascal>program IntToBinTest;
{$MODE objFPC}
{$MODE objFPC}
uses
uses
Line 4,039: Line 4,039:
IntBinTest(5);IntBinTest(50);IntBinTest(5000);
IntBinTest(5);IntBinTest(50);IntBinTest(5000);
IntBinTest(0);IntBinTest(NativeUint(-1));
IntBinTest(0);IntBinTest(NativeUint(-1));
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre> 5 101
<pre> 5 101
Line 4,051: Line 4,051:
Beware of the endianess of the constant.
Beware of the endianess of the constant.
I check performance with random Data.
I check performance with random Data.
<lang pascal>
<syntaxhighlight lang=pascal>
program IntToPcharTest;
program IntToPcharTest;
uses
uses
Line 4,157: Line 4,157:
Writeln(cnt/rounds+1:6:3);
Writeln(cnt/rounds+1:6:3);
FreeMem(s);
FreeMem(s);
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,173: Line 4,173:


=={{header|Peloton}}==
=={{header|Peloton}}==
<lang sgml><@ defbaslit>2</@>
<syntaxhighlight lang=sgml><@ defbaslit>2</@>


<@ saybaslit>0</@>
<@ saybaslit>0</@>
Line 4,179: Line 4,179:
<@ saybaslit>50</@>
<@ saybaslit>50</@>
<@ saybaslit>9000</@>
<@ saybaslit>9000</@>
</syntaxhighlight>
</lang>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>for (5, 50, 9000) {
<syntaxhighlight lang=perl>for (5, 50, 9000) {
printf "%b\n", $_;
printf "%b\n", $_;
}</lang>
}</syntaxhighlight>
<pre>
<pre>
101
101
Line 4,192: Line 4,192:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<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;">"%b\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</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;">"%b\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</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;">"%b\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">50</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;">"%b\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">50</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;">"%b\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9000</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;">"%b\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9000</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 4,205: Line 4,205:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>def printBinary
<syntaxhighlight lang=Phixmonti>def printBinary
"The decimal value " print dup print " should produce an output of " print
"The decimal value " print dup print " should produce an output of " print
20 int>bit
20 int>bit
Line 4,227: Line 4,227:
5 printBinary
5 printBinary
50 printBinary
50 printBinary
9000 printBinary</lang>
9000 printBinary</syntaxhighlight>


Other solution
Other solution
<lang Phixmonti>/# Rosetta Code problem: http://rosettacode.org/wiki/Binary_digits
<syntaxhighlight lang=Phixmonti>/# Rosetta Code problem: http://rosettacode.org/wiki/Binary_digits
by Galileo, 05/2022 #/
by Galileo, 05/2022 #/


Line 4,248: Line 4,248:
50 printBinary
50 printBinary
9000 printBinary
9000 printBinary
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>The decimal value 5 should produce an output of 101
<pre>The decimal value 5 should produce an output of 101
Line 4,257: Line 4,257:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang=php><?php
echo decbin(5);
echo decbin(5);
echo decbin(50);
echo decbin(50);
echo decbin(9000);</lang>
echo decbin(9000);</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 4,267: Line 4,267:


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat> foreach(I in [5,50,900])
<syntaxhighlight lang=Picat> foreach(I in [5,50,900])
println(to_binary_string(I))
println(to_binary_string(I))
end.</lang>
end.</syntaxhighlight>


{{out}}
{{out}}
Line 4,278: Line 4,278:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>: (bin 5)
<syntaxhighlight lang=PicoLisp>: (bin 5)
-> "101"
-> "101"


Line 4,285: Line 4,285:


: (bin 9000)
: (bin 9000)
-> "10001100101000"</lang>
-> "10001100101000"</syntaxhighlight>


=={{header|Piet}}==
=={{header|Piet}}==
Line 4,447: Line 4,447:
=={{header|PL/I}}==
=={{header|PL/I}}==
Displays binary output trivially, but with leading zeros:
Displays binary output trivially, but with leading zeros:
<lang pli>put edit (25) (B);</lang>
<syntaxhighlight lang=pli>put edit (25) (B);</syntaxhighlight>
{{out}}
{{out}}
<pre>Output: 0011001
<pre>Output: 0011001
</pre>
</pre>
With leading zero suppression:
With leading zero suppression:
<lang pli> declare text character (50) initial (' ');
<syntaxhighlight lang=pli> declare text character (50) initial (' ');


put string(text) edit (25) (b);
put string(text) edit (25) (b);
Line 4,458: Line 4,458:


put string(text) edit (2147483647) (b);
put string(text) edit (2147483647) (b);
put skip list (trim(text, '0'));</lang>
put skip list (trim(text, '0'));</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,466: Line 4,466:


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


/* CP/M BDOS CALL */
/* CP/M BDOS CALL */
Line 4,501: Line 4,501:


CALL BDOS(0,0);
CALL BDOS(0,0);
EOF</lang>
EOF</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 4,509: Line 4,509:
=={{header|PowerBASIC}}==
=={{header|PowerBASIC}}==
Pretty simple task in PowerBASIC since it has a built-in BIN$-Function. Omitting the second parameter ("Digits") means no leading zeros in the result.
Pretty simple task in PowerBASIC since it has a built-in BIN$-Function. Omitting the second parameter ("Digits") means no leading zeros in the result.
<lang powerbasic>
<syntaxhighlight lang=powerbasic>
#COMPILE EXE
#COMPILE EXE
#DIM ALL
#DIM ALL
Line 4,521: Line 4,521:
PRINT STR$(d(i)) & ": " & BIN$(d(i)) & " (" & BIN$(d(i), 32) & ")"
PRINT STR$(d(i)) & ": " & BIN$(d(i)) & " (" & BIN$(d(i), 32) & ")"
NEXT i
NEXT i
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>
{{out}}<pre>
{{out}}<pre>
5: 101 (00000000000000000000000000000101)
5: 101 (00000000000000000000000000000101)
Line 4,530: Line 4,530:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
{{libheader|Microsoft .NET Framework}}
{{libheader|Microsoft .NET Framework}}
<lang PowerShell>@(5,50,900) | foreach-object { [Convert]::ToString($_,2) }</lang>
<syntaxhighlight lang=PowerShell>@(5,50,900) | foreach-object { [Convert]::ToString($_,2) }</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 4,537: Line 4,537:


=={{header|Processing}}==
=={{header|Processing}}==
<lang processing>println(Integer.toBinaryString(5)); // 101
<syntaxhighlight lang=processing>println(Integer.toBinaryString(5)); // 101
println(Integer.toBinaryString(50)); // 110010
println(Integer.toBinaryString(50)); // 110010
println(Integer.toBinaryString(9000)); // 10001100101000</lang>
println(Integer.toBinaryString(9000)); // 10001100101000</syntaxhighlight>
Processing also has a binary() function, but this returns zero-padded results
Processing also has a binary() function, but this returns zero-padded results
<lang processing>println(binary(5)); // 00000000000101
<syntaxhighlight lang=processing>println(binary(5)); // 00000000000101
println(binary(50)); // 00000000110010
println(binary(50)); // 00000000110010
println(binary(9000)); // 10001100101000</lang>
println(binary(9000)); // 10001100101000</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
{{works with|SWI Prolog}}
{{works with|SWI Prolog}}
{{works with|GNU Prolog}}
{{works with|GNU Prolog}}
<lang prolog>
<syntaxhighlight lang=prolog>
binary(X) :- format('~2r~n', [X]).
binary(X) :- format('~2r~n', [X]).
main :- maplist(binary, [5,50,9000]), halt.
main :- maplist(binary, [5,50,9000]), halt.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>101
<pre>101
Line 4,558: Line 4,558:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>If OpenConsole()
<syntaxhighlight lang=PureBasic>If OpenConsole()
PrintN(Bin(5)) ;101
PrintN(Bin(5)) ;101
PrintN(Bin(50)) ;110010
PrintN(Bin(50)) ;110010
Line 4,565: Line 4,565:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 4,574: Line 4,574:
===String.format() method===
===String.format() method===
{{works with|Python|3.X and 2.6+}}
{{works with|Python|3.X and 2.6+}}
<lang python>>>> for i in range(16): print('{0:b}'.format(i))
<syntaxhighlight lang=python>>>> for i in range(16): print('{0:b}'.format(i))


0
0
Line 4,591: Line 4,591:
1101
1101
1110
1110
1111</lang>
1111</syntaxhighlight>


===Built-in bin() function===
===Built-in bin() function===
{{works with|Python|3.X and 2.6+}}
{{works with|Python|3.X and 2.6+}}
<lang python>>>> for i in range(16): print(bin(i)[2:])
<syntaxhighlight lang=python>>>> for i in range(16): print(bin(i)[2:])


0
0
Line 4,612: Line 4,612:
1101
1101
1110
1110
1111</lang>
1111</syntaxhighlight>
Pre-Python 2.6:
Pre-Python 2.6:
<lang python>>>> oct2bin = {'0': '000', '1': '001', '2': '010', '3': '011', '4': '100', '5': '101', '6': '110', '7': '111'}
<syntaxhighlight lang=python>>>> oct2bin = {'0': '000', '1': '001', '2': '010', '3': '011', '4': '100', '5': '101', '6': '110', '7': '111'}
>>> bin = lambda n: ''.join(oct2bin[octdigit] for octdigit in '%o' % n).lstrip('0') or '0'
>>> bin = lambda n: ''.join(oct2bin[octdigit] for octdigit in '%o' % n).lstrip('0') or '0'
>>> for i in range(16): print(bin(i))
>>> for i in range(16): print(bin(i))
Line 4,633: Line 4,633:
1101
1101
1110
1110
1111</lang>
1111</syntaxhighlight>


===Custom functions===
===Custom functions===


Defined in terms of a more general '''showIntAtBase''' function:
Defined in terms of a more general '''showIntAtBase''' function:
<lang python>'''Binary strings for integers'''
<syntaxhighlight lang=python>'''Binary strings for integers'''




Line 4,727: Line 4,727:


if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Mapping showBinary over integer list:
<pre>Mapping showBinary over integer list:
Line 4,741: Line 4,741:


Or, using a more specialised function to decompose an integer to a list of boolean values:
Or, using a more specialised function to decompose an integer to a list of boolean values:
<lang python>'''Decomposition of an integer to a string of booleans.'''
<syntaxhighlight lang=python>'''Decomposition of an integer to a string of booleans.'''




Line 4,861: Line 4,861:
# MAIN -------------------------------------------------
# MAIN -------------------------------------------------
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Mapping a composed function:
<pre>Mapping a composed function:
Line 4,874: Line 4,874:


=={{header|QB64}}==
=={{header|QB64}}==
<lang QB64>
<syntaxhighlight lang=QB64>
Print DecToBin$(5)
Print DecToBin$(5)
Print DecToBin$(50)
Print DecToBin$(50)
Line 4,925: Line 4,925:




</syntaxhighlight>
</lang>


=={{header|Quackery}}==
=={{header|Quackery}}==
Quackery provides built-in radix control, much like Forth.
Quackery provides built-in radix control, much like Forth.
<lang quackery>
<syntaxhighlight lang=quackery>
2 base put ( Numbers will be output in base 2 now. )
2 base put ( Numbers will be output in base 2 now. )
( Bases from 2 to 36 (inclusive) are supported. )
( Bases from 2 to 36 (inclusive) are supported. )
Line 4,939: Line 4,939:
base release ( It's best to clean up after ourselves. )
base release ( It's best to clean up after ourselves. )
( Numbers will be output in base 10 now. )
( Numbers will be output in base 10 now. )
</syntaxhighlight>
</lang>


A user-defined conversion might look something like this:
A user-defined conversion might look something like this:
<lang quackery>
<syntaxhighlight lang=quackery>
[ [] swap
[ [] swap
[ 2 /mod digit
[ 2 /mod digit
Line 4,953: Line 4,953:
50 bin echo$ cr
50 bin echo$ cr
9000 bin echo$ cr
9000 bin echo$ cr
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 4,962: Line 4,962:


=={{header|R}}==
=={{header|R}}==
<lang rsplus>
<syntaxhighlight lang=rsplus>
dec2bin <- function(num) {
dec2bin <- function(num) {
ifelse(num == 0,
ifelse(num == 0,
Line 4,973: Line 4,973:
cat(dec2bin(anumber),"\n")
cat(dec2bin(anumber),"\n")
}
}
</syntaxhighlight>
</lang>
'''output'''
'''output'''
<pre>
<pre>
Line 4,983: Line 4,983:


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang=racket>
#lang racket
#lang racket
;; Option 1: binary formatter
;; Option 1: binary formatter
Line 4,989: Line 4,989:
;; Option 2: explicit conversion
;; Option 2: explicit conversion
(for ([i 16]) (displayln (number->string i 2)))
(for ([i 16]) (displayln (number->string i 2)))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
{{works with|Rakudo|2015.12}}
{{works with|Rakudo|2015.12}}
<lang perl6>say .fmt("%b") for 5, 50, 9000;</lang>
<syntaxhighlight lang=raku line>say .fmt("%b") for 5, 50, 9000;</syntaxhighlight>
<pre>
<pre>
101
101
Line 5,003: Line 5,003:
Alternatively:
Alternatively:


<lang perl6>say .base(2) for 5, 50, 9000;</lang>
<syntaxhighlight lang=raku line>say .base(2) for 5, 50, 9000;</syntaxhighlight>
<pre>101
<pre>101
110010
110010
Line 5,009: Line 5,009:


=={{header|RapidQ}}==
=={{header|RapidQ}}==
<syntaxhighlight lang=vb>
<lang vb>
'Convert Integer to binary string
'Convert Integer to binary string
Print "bin 5 = ", bin$(5)
Print "bin 5 = ", bin$(5)
Line 5,015: Line 5,015:
Print "bin 9000 = ",bin$(9000)
Print "bin 9000 = ",bin$(9000)
sleep 10
sleep 10
</syntaxhighlight>
</lang>


=={{header|Red}}==
=={{header|Red}}==
<lang Red>Red []
<syntaxhighlight lang=Red>Red []


foreach number [5 50 9000] [
foreach number [5 50 9000] [
Line 5,025: Line 5,025:
print reduce [ pad/left number 5 binstr ]
print reduce [ pad/left number 5 binstr ]
]
]
</syntaxhighlight>
</lang>
'''output'''
'''output'''
<pre> 5 101
<pre> 5 101
Line 5,033: Line 5,033:


=={{header|Retro}}==
=={{header|Retro}}==
<lang Retro>9000 50 5 3 [ binary putn cr decimal ] times</lang>
<syntaxhighlight lang=Retro>9000 50 5 3 [ binary putn cr decimal ] times</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 5,040: Line 5,040:
Note: &nbsp; some REXX interpreters have a &nbsp; '''D2B''' &nbsp; [Decimal to Binary] &nbsp; BIF ('''b'''uilt-'''i'''n '''f'''unction).
Note: &nbsp; some REXX interpreters have a &nbsp; '''D2B''' &nbsp; [Decimal to Binary] &nbsp; BIF ('''b'''uilt-'''i'''n '''f'''unction).
<br>Programming note: &nbsp; this REXX version depends on &nbsp; '''numeric digits''' &nbsp; being large enough to handle leading zeroes in this manner (by adding a zero (to the binary version) to force superfluous leading zero suppression).
<br>Programming note: &nbsp; this REXX version depends on &nbsp; '''numeric digits''' &nbsp; being large enough to handle leading zeroes in this manner (by adding a zero (to the binary version) to force superfluous leading zero suppression).
<lang REXX>/*REXX program to convert several decimal numbers to binary (or base 2). */
<syntaxhighlight lang=REXX>/*REXX program to convert several decimal numbers to binary (or base 2). */
numeric digits 1000 /*ensure we can handle larger numbers. */
numeric digits 1000 /*ensure we can handle larger numbers. */
@.=; @.1= 0
@.=; @.1= 0
Line 5,050: Line 5,050:
y=x2b( d2x(@.j) ) + 0 /*force removal of extra leading zeroes*/
y=x2b( d2x(@.j) ) + 0 /*force removal of extra leading zeroes*/
say right(@.j,20) 'decimal, and in binary:' y /*display the number to the terminal. */
say right(@.j,20) 'decimal, and in binary:' y /*display the number to the terminal. */
end /*j*/ /*stick a fork in it, we're all done. */</lang>
end /*j*/ /*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output}}
{{out|output}}
<pre>
<pre>
Line 5,062: Line 5,062:
This version handles the case of zero as a special case more elegantly.
This version handles the case of zero as a special case more elegantly.
<br>The following versions depend on the setting of &nbsp; '''numeric digits''' &nbsp; such that the number in decimal can be expressed as a whole number.
<br>The following versions depend on the setting of &nbsp; '''numeric digits''' &nbsp; such that the number in decimal can be expressed as a whole number.
<lang REXX>/*REXX program to convert several decimal numbers to binary (or base 2). */
<syntaxhighlight lang=REXX>/*REXX program to convert several decimal numbers to binary (or base 2). */
@.=; @.1= 0
@.=; @.1= 0
@.2= 5
@.2= 5
Line 5,072: Line 5,072:
if y=='' then y=0 /*handle the special case of 0 (zero).*/
if y=='' then y=0 /*handle the special case of 0 (zero).*/
say right(@.j,20) 'decimal, and in binary:' y /*display the number to the terminal. */
say right(@.j,20) 'decimal, and in binary:' y /*display the number to the terminal. */
end /*j*/ /*stick a fork in it, we're all done. */</lang>
end /*j*/ /*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>


===concise version===
===concise version===
This version handles the case of zero a bit more obtusely, but concisely.
This version handles the case of zero a bit more obtusely, but concisely.
<lang REXX>/*REXX program to convert several decimal numbers to binary (or base 2). */
<syntaxhighlight lang=REXX>/*REXX program to convert several decimal numbers to binary (or base 2). */
@.=; @.1= 0
@.=; @.1= 0
@.2= 5
@.2= 5
Line 5,086: Line 5,086:
y=word( strip( x2b( d2x( @.j )), 'L', 0) 0, 1) /*elides all leading 0s, if null, use 0*/
y=word( strip( x2b( d2x( @.j )), 'L', 0) 0, 1) /*elides all leading 0s, if null, use 0*/
say right(@.j,20) 'decimal, and in binary:' y /*display the number to the terminal. */
say right(@.j,20) 'decimal, and in binary:' y /*display the number to the terminal. */
end /*j*/ /*stick a fork in it, we're all done. */</lang>
end /*j*/ /*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>


===conforming version===
===conforming version===
This REXX version conforms to the strict output requirements of this task (just show the binary output without any blanks).
This REXX version conforms to the strict output requirements of this task (just show the binary output without any blanks).
<lang REXX>/*REXX program to convert several decimal numbers to binary (or base 2). */
<syntaxhighlight lang=REXX>/*REXX program to convert several decimal numbers to binary (or base 2). */
numeric digits 200 /*ensure we can handle larger numbers. */
numeric digits 200 /*ensure we can handle larger numbers. */
@.=; @.1= 0
@.=; @.1= 0
Line 5,104: Line 5,104:
if y=='' then y=0 /*handle the special case of 0 (zero).*/
if y=='' then y=0 /*handle the special case of 0 (zero).*/
say y /*display binary number to the terminal*/
say y /*display binary number to the terminal*/
end /*j*/ /*stick a fork in it, we're all done. */</lang>
end /*j*/ /*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output}}
{{out|output}}
<pre>
<pre>
Line 5,116: Line 5,116:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang=ring>
see "Number to convert : "
see "Number to convert : "
give a
give a
Line 5,129: Line 5,129:
else see 0 ok
else see 0 ok
next
next
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>[5,50,9000].each do |n|
<syntaxhighlight lang=ruby>[5,50,9000].each do |n|
puts "%b" % n
puts "%b" % n
end</lang>
end</syntaxhighlight>
or
or
<lang ruby>for n in [5,50,9000]
<syntaxhighlight lang=ruby>for n in [5,50,9000]
puts n.to_s(2)
puts n.to_s(2)
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 5,145: Line 5,145:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>input "Number to convert:";a
<syntaxhighlight lang=runbasic>input "Number to convert:";a
while 2^(n+1) < a
while 2^(n+1) < a
n = n + 1
n = n + 1
Line 5,158: Line 5,158:
print 0;
print 0;
end if
end if
next</lang>
next</syntaxhighlight>
{{out}}
{{out}}
<pre>Number to convert:?9000
<pre>Number to convert:?9000
Line 5,164: Line 5,164:


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>fn main() {
<syntaxhighlight lang=rust>fn main() {
for i in 0..8 {
for i in 0..8 {
println!("{:b}", i)
println!("{:b}", i)
}
}
}</lang>
}</syntaxhighlight>
Outputs:
Outputs:
<pre>0
<pre>0
Line 5,180: Line 5,180:


=={{header|S-lang}}==
=={{header|S-lang}}==
<lang S-lang>define int_to_bin(d)
<syntaxhighlight lang=S-lang>define int_to_bin(d)
{
{
variable m = 0x40000000, prn = 0, bs = "";
variable m = 0x40000000, prn = 0, bs = "";
Line 5,200: Line 5,200:
() = printf("%s\n", int_to_bin(5));
() = printf("%s\n", int_to_bin(5));
() = printf("%s\n", int_to_bin(50));
() = printf("%s\n", int_to_bin(50));
() = printf("%s\n", int_to_bin(9000));</lang>
() = printf("%s\n", int_to_bin(9000));</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 5,208: Line 5,208:
=={{header|Scala}}==
=={{header|Scala}}==
Scala has an implicit conversion from <code>Int</code> to <code>RichInt</code> which has a method <code>toBinaryString</code>.
Scala has an implicit conversion from <code>Int</code> to <code>RichInt</code> which has a method <code>toBinaryString</code>.
<lang scala>scala> (5 toBinaryString)
<syntaxhighlight lang=scala>scala> (5 toBinaryString)
res0: String = 101
res0: String = 101


Line 5,215: Line 5,215:


scala> (9000 toBinaryString)
scala> (9000 toBinaryString)
res2: String = 10001100101000</lang>
res2: String = 10001100101000</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(display (number->string 5 2)) (newline)
<syntaxhighlight lang=scheme>(display (number->string 5 2)) (newline)
(display (number->string 50 2)) (newline)
(display (number->string 50 2)) (newline)
(display (number->string 9000 2)) (newline)</lang>
(display (number->string 9000 2)) (newline)</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
This example uses the [http://seed7.sourceforge.net/libraries/integer.htm#%28in_integer%29radix%28in_integer%29 radix] operator to write a number in binary.
This example uses the [http://seed7.sourceforge.net/libraries/integer.htm#%28in_integer%29radix%28in_integer%29 radix] operator to write a number in binary.


<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";


const proc: main is func
const proc: main is func
Line 5,234: Line 5,234:
writeln(number radix 2);
writeln(number radix 2);
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,257: Line 5,257:


=={{header|SequenceL}}==
=={{header|SequenceL}}==
<lang sequencel>main := toBinaryString([5, 50, 9000]);
<syntaxhighlight lang=sequencel>main := toBinaryString([5, 50, 9000]);


toBinaryString(number(0)) :=
toBinaryString(number(0)) :=
Line 5,265: Line 5,265:
toBinaryString(floor(number/2)) ++ val when floor(number/2) > 0
toBinaryString(floor(number/2)) ++ val when floor(number/2) > 0
else
else
val;</lang>
val;</syntaxhighlight>


{{out}}
{{out}}
Line 5,273: Line 5,273:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>[5, 50, 9000].each { |n|
<syntaxhighlight lang=ruby>[5, 50, 9000].each { |n|
say n.as_bin;
say n.as_bin;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 5,282: Line 5,282:


=={{header|Simula}}==
=={{header|Simula}}==
<lang simula>BEGIN
<syntaxhighlight lang=simula>BEGIN


PROCEDURE OUTINTBIN(N); INTEGER N;
PROCEDURE OUTINTBIN(N); INTEGER N;
Line 5,296: Line 5,296:
END;
END;


END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,306: Line 5,306:
=={{header|SkookumScript}}==
=={{header|SkookumScript}}==


<lang javascript>println(5.binary)
<syntaxhighlight lang=javascript>println(5.binary)
println(50.binary)
println(50.binary)
println(9000.binary)</lang>
println(9000.binary)</syntaxhighlight>
Or looping over a list of numbers:
Or looping over a list of numbers:
<lang javascript>{5 50 9000}.do[println(item.binary)]</lang>
<syntaxhighlight lang=javascript>{5 50 9000}.do[println(item.binary)]</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 5,317: Line 5,317:


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>5 printOn: Stdout radix:2
<syntaxhighlight lang=smalltalk>5 printOn: Stdout radix:2
50 printOn: Stdout radix:2
50 printOn: Stdout radix:2
9000 printOn: Stdout radix:2</lang>
9000 printOn: Stdout radix:2</syntaxhighlight>
or:
or:
<lang smalltalk>#(5 50 9000) do:[:each | each printOn: Stdout radix:2. Stdout cr]</lang>
<syntaxhighlight lang=smalltalk>#(5 50 9000) do:[:each | each printOn: Stdout radix:2. Stdout cr]</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
<lang snobol4>
<syntaxhighlight lang=snobol4>
define('bin(n,r)') :(bin_end)
define('bin(n,r)') :(bin_end)
bin bin = le(n,0) r :s(return)
bin bin = le(n,0) r :s(return)
Line 5,333: Line 5,333:
output = bin(50)
output = bin(50)
output = bin(9000)
output = bin(9000)
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,342: Line 5,342:


=={{header|SNUSP}}==
=={{header|SNUSP}}==
<lang SNUSP>
<syntaxhighlight lang=SNUSP>
/recurse\
/recurse\
$,binary!\@\>?!\@/<@\.#
$,binary!\@\>?!\@/<@\.#
Line 5,348: Line 5,348:
/<+>- \ div2
/<+>- \ div2
\?!#-?/+# mod2
\?!#-?/+# mod2
</syntaxhighlight>
</lang>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>print (Int.fmt StringCvt.BIN 5 ^ "\n");
<syntaxhighlight lang=sml>print (Int.fmt StringCvt.BIN 5 ^ "\n");
print (Int.fmt StringCvt.BIN 50 ^ "\n");
print (Int.fmt StringCvt.BIN 50 ^ "\n");
print (Int.fmt StringCvt.BIN 9000 ^ "\n");</lang>
print (Int.fmt StringCvt.BIN 9000 ^ "\n");</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang Swift>for num in [5, 50, 9000] {
<syntaxhighlight lang=Swift>for num in [5, 50, 9000] {
println(String(num, radix: 2))
println(String(num, radix: 2))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,366: Line 5,366:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>proc num2bin num {
<syntaxhighlight lang=tcl>proc num2bin num {
# Convert to _fixed width_ big-endian 32-bit binary
# Convert to _fixed width_ big-endian 32-bit binary
binary scan [binary format "I" $num] "B*" binval
binary scan [binary format "I" $num] "B*" binval
# Strip useless leading zeros by reinterpreting as a big decimal integer
# Strip useless leading zeros by reinterpreting as a big decimal integer
scan $binval "%lld"
scan $binval "%lld"
}</lang>
}</syntaxhighlight>
Demonstrating:
Demonstrating:
<lang tcl>for {set x 0} {$x < 16} {incr x} {
<syntaxhighlight lang=tcl>for {set x 0} {$x < 16} {incr x} {
puts [num2bin $x]
puts [num2bin $x]
}
}
Line 5,379: Line 5,379:
puts [num2bin 5]
puts [num2bin 5]
puts [num2bin 50]
puts [num2bin 50]
puts [num2bin 9000]</lang>
puts [num2bin 9000]</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,405: Line 5,405:
<br>
<br>
Or you can use the builtin format:
Or you can use the builtin format:
<lang tcl>foreach n {0 1 5 50 9000} {
<syntaxhighlight lang=tcl>foreach n {0 1 5 50 9000} {
puts [format "%4u: %b" $n $n]
puts [format "%4u: %b" $n $n]
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> 0: 0
<pre> 0: 0
Line 5,417: Line 5,417:
=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
Using Standard TI-83 BASIC
Using Standard TI-83 BASIC
<lang ti83b>PROGRAM:BINARY
<syntaxhighlight lang=ti83b>PROGRAM:BINARY
:Disp "NUMBER TO"
:Disp "NUMBER TO"
:Disp "CONVERT:"
:Disp "CONVERT:"
Line 5,435: Line 5,435:
:N-1→N
:N-1→N
:End
:End
:Disp B</lang>
:Disp B</syntaxhighlight>
Alternate using a string to display larger numbers.
Alternate using a string to display larger numbers.
<lang ti83b>PROGRAM:BINARY
<syntaxhighlight lang=ti83b>PROGRAM:BINARY
:Input X
:Input X
:" "→Str1
:" "→Str1
Line 5,445: Line 5,445:
:iPart(X)→X
:iPart(X)→X
:End
:End
:Str1</lang>
:Str1</syntaxhighlight>
Using the baseInput() "real(25," function from [http://www.detachedsolutions.com/omnicalc/ Omnicalc]
Using the baseInput() "real(25," function from [http://www.detachedsolutions.com/omnicalc/ Omnicalc]
<lang ti83b>PROGRAM:BINARY
<syntaxhighlight lang=ti83b>PROGRAM:BINARY
:Disp "NUMBER TO"
:Disp "NUMBER TO"
:Disp "CONVERT"
:Disp "CONVERT"
:Input "Str1"
:Input "Str1"
:Disp real(25,Str1,10,2)</lang>
:Disp real(25,Str1,10,2)</syntaxhighlight>


More compact version:
More compact version:
<lang ti83b>:Input "DEC: ",D
<syntaxhighlight lang=ti83b>:Input "DEC: ",D
:" →Str1
:" →Str1
:If not(D:"0→Str1
:If not(D:"0→Str1
Line 5,466: Line 5,466:
:End
:End
:Disp Str1
:Disp Str1
</syntaxhighlight>
</lang>


=={{header|uBasic/4tH}}==
=={{header|uBasic/4tH}}==
This will convert any decimal number to any base between 2 and 16.
This will convert any decimal number to any base between 2 and 16.
<lang>Do
<syntaxhighlight lang=text>Do
Input "Enter base (1<X<17): "; b
Input "Enter base (1<X<17): "; b
While (b < 2) + (b > 16)
While (b < 2) + (b > 16)
Line 5,502: Line 5,502:
130 Print "D"; : Return
130 Print "D"; : Return
140 Print "E"; : Return
140 Print "E"; : Return
150 Print "F"; : Return</lang>
150 Print "F"; : Return</syntaxhighlight>
{{out}}
{{out}}
<pre>Enter base (1<X<17): 2
<pre>Enter base (1<X<17): 2
Line 5,511: Line 5,511:


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
<lang sh># Define a function to output binary digits
<syntaxhighlight lang=sh># Define a function to output binary digits
tobinary() {
tobinary() {
# We use the bench calculator for our conversion
# We use the bench calculator for our conversion
Line 5,519: Line 5,519:
# Call the function with each of our values
# Call the function with each of our values
tobinary 5
tobinary 5
tobinary 50</lang>
tobinary 50</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
Line 5,541: Line 5,541:
Places is useful for padding the return value with leading 0s (zeros).
Places is useful for padding the return value with leading 0s (zeros).


<syntaxhighlight lang=vb>
<lang vb>
Option Explicit
Option Explicit


Line 5,580: Line 5,580:
End If
End If
End Function
End Function
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>The decimal value 5 should produce an output of : 101
<pre>The decimal value 5 should produce an output of : 101
Line 5,591: Line 5,591:
=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
This implementation reads the numeric values from user input and writes the converted binary values in the edit buffer.
This implementation reads the numeric values from user input and writes the converted binary values in the edit buffer.
<lang vedit>repeat (ALL) {
<syntaxhighlight lang=vedit>repeat (ALL) {
#10 = Get_Num("Give a numeric value, -1 to end: ", STATLINE)
#10 = Get_Num("Give a numeric value, -1 to end: ", STATLINE)
if (#10 < 0) { break }
if (#10 < 0) { break }
Line 5,607: Line 5,607:
EOL
EOL
Ins_Newline
Ins_Newline
Return </lang>
Return </syntaxhighlight>
Example output when values 0, 1, 5, 50 and 9000 were entered:
Example output when values 0, 1, 5, 50 and 9000 were entered:
<pre>
<pre>
Line 5,618: Line 5,618:


=={{header|Vim Script}}==
=={{header|Vim Script}}==
<lang vim>function Num2Bin(n)
<syntaxhighlight lang=vim>function Num2Bin(n)
let n = a:n
let n = a:n
let s = ""
let s = ""
Line 5,638: Line 5,638:
echo Num2Bin(5)
echo Num2Bin(5)
echo Num2Bin(50)
echo Num2Bin(50)
echo Num2Bin(9000)</lang>
echo Num2Bin(9000)</syntaxhighlight>


{{Out}}
{{Out}}
Line 5,647: Line 5,647:
=={{header|Visual Basic}}==
=={{header|Visual Basic}}==
{{works with|Visual Basic|VB6 Standard}}
{{works with|Visual Basic|VB6 Standard}}
<syntaxhighlight lang=vb>
<lang vb>
Public Function Bin(ByVal l As Long) As String
Public Function Bin(ByVal l As Long) As String
Dim i As Long
Dim i As Long
Line 5,682: Line 5,682:
Debug.Print Bin(9000)
Debug.Print Bin(9000)
End Sub
End Sub
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>101
<pre>101
Line 5,689: Line 5,689:


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
<lang vbnet>Module Program
<syntaxhighlight lang=vbnet>Module Program
Sub Main
Sub Main
For Each number In {5, 50, 9000}
For Each number In {5, 50, 9000}
Line 5,695: Line 5,695:
Next
Next
End Sub
End Sub
End Module</lang>
End Module</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 5,702: Line 5,702:


=={{header|Visual FoxPro}}==
=={{header|Visual FoxPro}}==
<lang vfp>
<syntaxhighlight lang=vfp>
*!* Binary Digits
*!* Binary Digits
CLEAR
CLEAR
Line 5,728: Line 5,728:
RETURN FLOOR(v)
RETURN FLOOR(v)
ENDFUNC
ENDFUNC
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 5,740: Line 5,740:
This program prints binary numbers until the internal representation of the current integer overflows to -1; it will never do so on some interpreters. It is almost an exact duplicate of [[Count in octal#Whitespace]].
This program prints binary numbers until the internal representation of the current integer overflows to -1; it will never do so on some interpreters. It is almost an exact duplicate of [[Count in octal#Whitespace]].


<lang Whitespace>
<syntaxhighlight lang=Whitespace>


Line 5,779: Line 5,779:




</lang>
</syntaxhighlight>


It was generated from the following pseudo-Assembly.
It was generated from the following pseudo-Assembly.


<lang asm>push 0
<syntaxhighlight lang=asm>push 0
; Increment indefinitely.
; Increment indefinitely.
0:
0:
Line 5,815: Line 5,815:
3:
3:
pop
pop
ret</lang>
ret</syntaxhighlight>


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang vlang>fn main() {
<syntaxhighlight lang=vlang>fn main() {
for i in 0..16 {
for i in 0..16 {
println("${i:b}")
println("${i:b}")
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,844: Line 5,844:


=={{header|VTL-2}}==
=={{header|VTL-2}}==
<lang VTL2>10 N=5
<syntaxhighlight lang=VTL2>10 N=5
20 #=100
20 #=100
30 N=50
30 N=50
Line 5,859: Line 5,859:
180 #=I<18*160
180 #=I<18*160
190 ?=""
190 ?=""
200 #=;</lang>
200 #=;</syntaxhighlight>
{{out}}
{{out}}
<pre>101
<pre>101
Line 5,867: Line 5,867:
=={{header|Wortel}}==
=={{header|Wortel}}==
Using JavaScripts buildin toString method on the Number object, the following function takes a number and returns a string with the binary representation:
Using JavaScripts buildin toString method on the Number object, the following function takes a number and returns a string with the binary representation:
<lang wortel>\.toString 2
<syntaxhighlight lang=wortel>\.toString 2
; the following function also casts the string to a number
; the following function also casts the string to a number
^(@+ \.toString 2)</lang>
^(@+ \.toString 2)</syntaxhighlight>
To output to the console:
To output to the console:
<lang wortel>@each ^(console.log \.toString 2) [5 50 900]</lang>
<syntaxhighlight lang=wortel>@each ^(console.log \.toString 2) [5 50 900]</syntaxhighlight>
Outputs: <pre>
Outputs: <pre>
101
101
Line 5,879: Line 5,879:
=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "/fmt" for Fmt
<syntaxhighlight lang=ecmascript>import "/fmt" for Fmt
System.print("Converting to binary:")
System.print("Converting to binary:")
for (i in [5, 50, 9000]) Fmt.print("$d -> $b", i, i)</lang>
for (i in [5, 50, 9000]) Fmt.print("$d -> $b", i, i)</syntaxhighlight>


{{out}}
{{out}}
Line 5,894: Line 5,894:
=={{header|X86 Assembly}}==
=={{header|X86 Assembly}}==
Translation of XPL0. Assemble with tasm, tlink /t
Translation of XPL0. Assemble with tasm, tlink /t
<lang asm> .model tiny
<syntaxhighlight lang=asm> .model tiny
.code
.code
.486
.486
Line 5,922: Line 5,922:
int 29h ;display character
int 29h ;display character
ret
ret
end start</lang>
end start</syntaxhighlight>


{{out}}
{{out}}
Line 5,932: Line 5,932:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes; \intrinsic code declarations
<syntaxhighlight lang=XPL0>include c:\cxpl\codes; \intrinsic code declarations


proc BinOut(N); \Output N in binary
proc BinOut(N); \Output N in binary
Line 5,948: Line 5,948:
I:= I+1;
I:= I+1;
until KeyHit or I=0;
until KeyHit or I=0;
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 5,969: Line 5,969:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang yabasic>dim a(3)
<syntaxhighlight lang=yabasic>dim a(3)
a(0) = 5
a(0) = 5
a(1) = 50
a(1) = 50
Line 5,977: Line 5,977:
print a(i) using "####", " -> ", bin$(a(i))
print a(i) using "####", " -> ", bin$(a(i))
next i
next i
end</lang>
end</syntaxhighlight>


=={{header|Z80 Assembly}}==
=={{header|Z80 Assembly}}==
{{trans|8086 Assembly}}
{{trans|8086 Assembly}}


<lang z80>org &8000
<syntaxhighlight lang=z80>org &8000
PrintChar equ &BB5A ;syscall - prints accumulator to Amstrad CPC's screen
PrintChar equ &BB5A ;syscall - prints accumulator to Amstrad CPC's screen


Line 6,054: Line 6,054:
call &BB5A
call &BB5A
ld a,10
ld a,10
jp &BB5A ;its ret will return for us.</lang>
jp &BB5A ;its ret will return for us.</syntaxhighlight>




This is another version. Output of the result over port 0A hex.
This is another version. Output of the result over port 0A hex.
<lang z80>
<syntaxhighlight lang=z80>
; HL contains the value to be converted
; HL contains the value to be converted
ld hl,5
ld hl,5
Line 6,104: Line 6,104:
djnz bitloop
djnz bitloop


ret</lang>
ret</syntaxhighlight>




=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>(9000).toString(2)</lang>
<syntaxhighlight lang=zkl>(9000).toString(2)</syntaxhighlight>
<lang zkl>T(5,50,9000).apply("toString",2) //--> L("101","110010","10001100101000")</lang>
<syntaxhighlight lang=zkl>T(5,50,9000).apply("toString",2) //--> L("101","110010","10001100101000")</syntaxhighlight>
<lang zkl>"%.2B".fmt(9000)</lang>
<syntaxhighlight lang=zkl>"%.2B".fmt(9000)</syntaxhighlight>


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
<lang zxbasic>10 LET n=5: GO SUB 1000: PRINT s$
<syntaxhighlight lang=zxbasic>10 LET n=5: GO SUB 1000: PRINT s$
20 LET n=50: GO SUB 1000: PRINT s$
20 LET n=50: GO SUB 1000: PRINT s$
30 LET n=9000: GO SUB 1000: PRINT s$
30 LET n=9000: GO SUB 1000: PRINT s$
Line 6,127: Line 6,127:
1070 IF (sf <> 0) THEN LET s$=s$+d$
1070 IF (sf <> 0) THEN LET s$=s$+d$
1080 NEXT l
1080 NEXT l
1090 RETURN</lang>
1090 RETURN</syntaxhighlight>