Binary digits: Difference between revisions

PascalABC.NET
(→‎{{header|MiniScript}}: added iterative solution)
(PascalABC.NET)
(139 intermediate revisions by 56 users not shown)
Line 1:
{{task|Basic language learning}}
[[Category:Radices]]
{{task|Basic language learning}}
 
;Task:
Line 15:
There should be no other whitespace, radix or sign markers in the produced output, and [[wp:Leading zero|leading zeros]] should not appear in the results.
<br><br>
=={{header|8th}}==
 
<syntaxhighlight lang="forth">
=={{header|0815}}==
2 base drop
<lang 0815>}:r:|~ Read numbers in a loop.
#50 . cr
}:b: Treat the queue as a stack and
</syntaxhighlight>
<:2:= accumulate the binary digits
/=>&~ of the given number.
^:b:
<:0:-> Enqueue negative 1 as a sentinel.
{ Dequeue the first binary digit.
}:p:
~%={+ Rotate each binary digit into place and print it.
^:p:
<:a:~$ Output a newline.
^:r:</lang>
 
{{out}}
<pre>
 
Note that 0815 reads numeric input in hexadecimal.
 
<lang bash>echo -e "5\n32\n2329" | 0815 bin.0
101
110010
</pre>
10001100101001</lang>
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">L(n) [0, 5, 50, 9000]
print(‘#4 = #.’.format(n, bin(n)))</langsyntaxhighlight>
{{out}}
<pre>
Line 49 ⟶ 34:
9000 = 10001100101000
</pre>
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Binary digits 27/08/2015
BINARY CSECT
USING BINARY,R12
Line 93 ⟶ 77:
CBIN DC CL32' ' binary value
YREGS
END BINARY</langsyntaxhighlight>
{{out}}
<pre>
Line 101 ⟶ 85:
9000 10001100101000
</pre>
=={{header|0815}}==
<syntaxhighlight lang="0815">}:r:|~ Read numbers in a loop.
}:b: Treat the queue as a stack and
<:2:= accumulate the binary digits
/=>&~ of the given number.
^:b:
<:0:-> Enqueue negative 1 as a sentinel.
{ Dequeue the first binary digit.
}:p:
~%={+ Rotate each binary digit into place and print it.
^:p:
<:a:~$ Output a newline.
^:r:</syntaxhighlight>
 
{{out}}
 
Note that 0815 reads numeric input in hexadecimal.
 
<syntaxhighlight lang="bash">echo -e "5\n32\n2329" | 0815 bin.0
101
110010
10001100101001</syntaxhighlight>
=={{header|6502 Assembly}}==
{{works with|http://vice-emu.sourceforge.net/ VICE}}
Line 122 ⟶ 127:
strout = $cb1e
</pre>
<langsyntaxhighlight lang="6502asm">
; C64 - Binary digits
; http://rosettacode.org/wiki/Binary_digits
Line 213 ⟶ 218:
binstr .repeat 16, $00 ; reserve 16 bytes for the binary digits
.byte $0d, $00 ; newline + null terminator
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 228 ⟶ 233:
100
</pre>
=={{header|8080 Assembly}}==
<syntaxhighlight lang="8080asm">bdos: equ 5h ; CP/M system call
puts: equ 9h ; Print string
org 100h
lxi h,5 ; Print value for 5
call prbin
lxi h,50 ; Print value for 50
call prbin
lxi h,9000 ; Print value for 9000
prbin: call bindgt ; Make binary representation of HL
mvi c,puts ; Print it
jmp bdos
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Return the binary representation of the 16-bit number in HL
;;; as a string starting at [DE].
bindgt: lxi d,binend ; End of binary string
ana a ; Clear carry flag
binlp: dcx d ; Previous digit
mov a,h ; Shift HL left, LSB into carry flag
rar
mov h,a
mov a,l
rar
mov l,a
mvi a,'0' ; Digit '0' or '1' depending on
aci 0 ; status of carry flag.
stax d
mov a,h ; Is HL 0 now?
ora l
rz ; Then stop
jmp binlp ; Otherwise, do next bit
binstr: db '0000000000000000' ; Placeholder for string
binend: db 13,10,'$' ; end with \r\n </syntaxhighlight>
 
=={{header|8th}}==
<lang forth>
2 base drop
#50 . cr
</lang>
{{out}}
 
<pre>
<pre>101
110010
10001100101000
 
</pre>
=={{header|8086 Assembly}}==
<syntaxhighlight lang="asm"> .model small
.stack 1024
.data
 
TestData0 byte 5,255 ;255 is the terminator
TestData1 byte 5,0,255
TestData2 byte 9,0,0,0,255
.code
start:
 
mov ax,@data
mov ds,ax
cld ;String functions are set to auto-increment
mov ax,2 ;clear screen by setting video mode to 0
int 10h ;select text mode - We're already in it, so this clears the screen
mov si,offset TestData0
call PrintBinary_NoLeadingZeroes
 
mov si,offset TestData1
call PrintBinary_NoLeadingZeroes
 
mov si,offset TestData2
call PrintBinary_NoLeadingZeroes
ExitDOS:
mov ax,4C00h ;return to dos
int 21h
PrintBinary_NoLeadingZeroes proc
;input: DS:SI = seg:offset of a 255-terminated sequence of unpacked BCD digits, stored big-endian
;setup
mov bx,8000h
;bl will be our "can we print zeroes yet" flag.
;bh is the "revolving bit mask" - we'll compare each bit to it, then rotate it right once.
; It's very handy because it's a self-resetting loop counter as well!
 
NextDigit:
lodsb
cmp al,255
je Terminated
NextBit:
test al,bh ;is the bit we're testing right now set?
jz PrintZero
;else, print one
push ax
mov dl,'1' ;31h
mov ah,2
int 21h ;prints the ascii code in DL
pop ax
or bl,1 ;set "we've printed a one" flag
jmp predicate
PrintZero:
test bl,bl
jz predicate
push ax
mov dl,'0' ;30h
mov ah,2
int 21h
pop ax
predicate:
ror bh,1
jnc NextBit
;if the carry is set, we've rotated BH back to 10000000b,
; so move on to the next digit in that case.
jmp NextDigit
Terminated:
push ax
mov ah,2
mov dl,13 ;carriage return
int 21h
mov dl,10 ;linefeed
int 21h
pop ax
ret
PrintBinary_NoLeadingZeroes endp</syntaxhighlight>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program binarydigit.s */
 
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
 
 
/*******************************************/
/* Initialized data */
/*******************************************/
.data
sMessAffBindeb: .asciz "The decimal value "
sMessAffBin: .asciz " should produce an output of "
szRetourLigne: .asciz "\n"
 
/*******************************************/
/* Uninitialized data */
/*******************************************/
.bss
sZoneConv: .skip 100
sZoneBin: .skip 100
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: /* entry of program */
mov x5,5
mov x0,x5
ldr x1,qAdrsZoneConv
bl conversion10S
mov x0,x5
ldr x1,qAdrsZoneBin
bl conversion2 // binary conversion and display résult
ldr x0,qAdrsZoneBin
ldr x0,qAdrsMessAffBindeb
bl affichageMess
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrsMessAffBin
bl affichageMess
ldr x0,qAdrsZoneBin
bl affichageMess
ldr x0,qAdrszRetourLigne
bl affichageMess
/* other number */
mov x5,50
mov x0,x5
ldr x1,qAdrsZoneConv
bl conversion10S
mov x0,x5
ldr x1,qAdrsZoneBin
bl conversion2 // binary conversion and display résult
ldr x0,qAdrsZoneBin
ldr x0,qAdrsMessAffBindeb
bl affichageMess
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrsMessAffBin
bl affichageMess
ldr x0,qAdrsZoneBin
bl affichageMess
ldr x0,qAdrszRetourLigne
bl affichageMess
/* other number */
mov x5,-1
mov x0,x5
ldr x1,qAdrsZoneConv
bl conversion10S
mov x0,x5
ldr x1,qAdrsZoneBin
bl conversion2 // binary conversion and display résult
ldr x0,qAdrsZoneBin
ldr x0,qAdrsMessAffBindeb
bl affichageMess
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrsMessAffBin
bl affichageMess
ldr x0,qAdrsZoneBin
bl affichageMess
ldr x0,qAdrszRetourLigne
bl affichageMess
/* other number */
mov x5,1
mov x0,x5
ldr x1,qAdrsZoneConv
bl conversion10S
mov x0,x5
ldr x1,qAdrsZoneBin
bl conversion2 // binary conversion and display résult
ldr x0,qAdrsZoneBin
ldr x0,qAdrsMessAffBindeb
bl affichageMess
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrsMessAffBin
bl affichageMess
ldr x0,qAdrsZoneBin
bl affichageMess
ldr x0,qAdrszRetourLigne
bl affichageMess
 
 
100: // standard end of the program */
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrsZoneBin: .quad sZoneBin
qAdrsMessAffBin: .quad sMessAffBin
qAdrsMessAffBindeb: .quad sMessAffBindeb
qAdrszRetourLigne: .quad szRetourLigne
/******************************************************************/
/* register conversion in binary */
/******************************************************************/
/* x0 contains the register */
/* x1 contains the address of receipt area */
conversion2:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
clz x2,x0 // number of left zeros bits
mov x3,64
sub x2,x3,x2 // number of significant bits
strb wzr,[x1,x2] // store 0 final
sub x3,x2,1 // position counter of the written character
2: // loop
tst x0,1 // test first bit
lsr x0,x0,#1 // shift right one bit
bne 3f
mov x4,#48 // bit = 0 => character '0'
b 4f
3:
mov x4,#49 // bit = 1 => character '1'
4:
strb w4,[x1,x3] // character in reception area at position counter
sub x3,x3,#1
subs x2,x2,#1 // 0 bits ?
bgt 2b // no! loop
 
100:
ldp x3,x4,[sp],16 // restaur 2 registres
ldp x2,lr,[sp],16 // restaur 2 registres
ret // retour adresse lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
 
</syntaxhighlight>
{{out}}
<pre>
The decimal value +5 should produce an output of 101
The decimal value +50 should produce an output of 110010
The decimal value -1 should produce an output of 1111111111111111111111111111111111111111111111111111111111111111
The decimal value +1 should produce an output of 1
</pre>
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(include-book "arithmetic-3/top" :dir :system)
 
(defun bin-string-r (x)
Line 253 ⟶ 539:
(if (zp x)
"0"
(bin-string-r x)))</langsyntaxhighlight>
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC PrintBinary(CARD v)
CHAR ARRAY a(16)
BYTE i=[0]
 
DO
a(i)=(v&1)+'0
i==+1
v=v RSH 1
UNTIL v=0
OD
 
DO
i==-1
Put(a(i))
UNTIL i=0
OD
RETURN
 
PROC Main()
CARD ARRAY data=[0 5 50 9000]
BYTE i
CARD v
 
FOR i=0 TO 3
DO
v=data(i)
PrintF("Output for %I is ",v)
PrintBinary(v)
PutE()
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Binary_digits.png Screenshot from Atari 8-bit computer]
<pre>
Output for 0 is 0
Output for 5 is 101
Output for 50 is 110010
Output for 9000 is 10001100101000
</pre>
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">wwithwith ada.text_io; use ada.text_io;
procedure binary is
bit : array (0..1) of character := ('0','1');
Line 269 ⟶ 594:
put_line ("Output for" & test'img & " is " & bin_image (test));
end loop;
end binary;</langsyntaxhighlight>
 
{{out}}
Line 277 ⟶ 602:
Output for 9000 is 10001100101000
</pre>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">o_xinteger(2, 0);
o_byte('\n');
o_xinteger(2, 5);
Line 285 ⟶ 609:
o_xinteger(2, 50);
o_byte('\n');
o_form("/x2/\n", 9000);</langsyntaxhighlight>
{{out}}
<pre>0
Line 291 ⟶ 615:
110010
10001100101000</pre>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68|Revision 1.}}
{{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''.}}
'''File: Binary_digits.a68'''<langsyntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #
 
printf((
Line 309 ⟶ 632:
50, " => ", []BOOL(BIN 50)[bits width-6+1:], new line,
9000, " => ", []BOOL(BIN 9000)[bits width-14+1:], new line
))</langsyntaxhighlight>
{{out}}
<pre>
Line 319 ⟶ 642:
+9000 => TFFFTTFFTFTFFF
</pre>
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% prints an integer in binary - the number must be greater than zero %
procedure printBinaryDigits( integer value n ) ;
Line 344 ⟶ 666:
end
 
end.</langsyntaxhighlight>
=={{header|ALGOL-M}}==
<syntaxhighlight lang="algolm">begin
procedure writebin(n);
integer n;
begin
procedure inner(x);
integer x;
begin
if x>1 then inner(x/2);
writeon(if x-x/2*2=0 then "0" else "1");
end;
write(""); % start new line %
inner(n);
end;
 
writebin(5);
writebin(50);
writebin(9000);
end</syntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|APL}}==
Works in: [[Dyalog APL]]
 
A builtin function. Produces a boolean array.
<syntaxhighlight lang="apl">base2←2∘⊥⍣¯1</syntaxhighlight>
 
 
Works in: [[GNU APL]]
 
Produces a boolean array.
<syntaxhighlight lang="apl">base2 ← {((⌈2⍟⍵+1)⍴2)⊤⍵}</syntaxhighlight>
 
NOTE: Both versions above will yield an empty boolean array for 0.
 
<pre>
base2 0
 
base2 5
1 0 1
base2 50
1 1 0 0 1 0
base2 9000
1 0 0 0 1 1 0 0 1 0 1 0 0 0
</pre>
=={{header|AppleScript}}==
===Functional===
{{Trans|JavaScript}}
(ES6 version)
 
(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)
<syntaxhighlight lang="applescript">---------------------- BINARY STRING -----------------------
<lang AppleScript>-- showBin :: Int -> String
 
-- showBin :: Int -> String
on showBin(n)
script binaryChar
Line 362 ⟶ 732:
end showBin
 
 
-- GENERIC FUNCTIONS ----------------------------------------------------------
--------------------------- TEST ---------------------------
on run
script
on |λ|(n)
intercalate(" -> ", {n as string, showBin(n)})
end |λ|
end script
return unlines(map(result, {5, 50, 9000}))
end run
 
 
-------------------- GENERIC FUNCTIONS ---------------------
 
-- showIntAtBase :: Int -> (Int -> Char) -> Int -> String -> String
Line 386 ⟶ 769:
end if
end showIntAtBase
 
 
-- quotRem :: Integral a => a -> a -> (a, a)
Line 392 ⟶ 776:
end quotRem
 
-- TEST -----------------------------------------------------------------------
on run
script
on |λ|(n)
intercalate(" -> ", {n as string, showBin(n)})
end |λ|
end script
return unlines(map(result, {5, 50, 9000}))
end run
 
-------------------- GENERICS FOR TEST ---------------------
 
-- GENERIC FUNCTIONS FOR TEST -------------------------------------------------
 
-- intercalate :: Text -> [Text] -> Text
Line 413 ⟶ 786:
return strJoined
end intercalate
 
 
-- map :: (a -> b) -> [a] -> [b]
Line 425 ⟶ 799:
end tell
end map
 
 
-- Lift 2nd class handler function into 1st class script wrapper
Line 441 ⟶ 816:
on unlines(xs)
intercalate(linefeed, xs)
end unlines</langsyntaxhighlight>
{{Out}}
<pre>5 -> 101
50 -> 110010
9000 -> 10001100101000</pre>
 
Or using:
Or,using:
<langsyntaxhighlight AppleScriptlang="applescript">-- showBin :: Int -> String
on showBin(n)
script binaryChar
Line 456 ⟶ 830:
end script
showIntAtBase(2, binaryChar, n, "")
end showBin</langsyntaxhighlight>
{{Out}}
<pre>5 -> 一〇一
50 -> 一一〇〇一〇
9000 -> 一〇〇〇一一〇〇一〇一〇〇〇</pre>
 
=== Straightforward ===
 
At its very simplest, an AppleScript solution would look something like this:
 
<syntaxhighlight lang="applescript">on intToBinary(n)
set binary to (n mod 2 div 1) as text
set n to n div 2
repeat while (n > 0)
set binary to ((n mod 2 div 1) as text) & binary
set n to n div 2
end repeat
return binary
end intToBinary
 
display dialog ¬
intToBinary(5) & linefeed & ¬
intToBinary(50) & linefeed & ¬
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:
 
<syntaxhighlight lang="applescript">on intToBinary(n)
set binary to ""
repeat
-- Calculate an integer value whose 8 decimal digits are the same as the low 8 binary digits of n's current value.
set binAsDec to (n div 128 mod 2 * 10000000 + n div 64 mod 2 * 1000000 + n div 32 mod 2 * 100000 + ¬
n div 16 mod 2 * 10000 + n div 8 mod 2 * 1000 + n div 4 mod 2 * 100 + n div 2 mod 2 * 10 + n mod 2) div 1
-- Coerce to text as appropriate, prepend to the output text, and prepare to get another 8 digits or not as necessary.
if (n > 255) then
set binary to text 2 thru -1 of ((100000000 + binAsDec) as text) & binary
set n to n div 256
else
set binary to (binAsDec as text) & binary
exit repeat
end if
end repeat
return binary
end intToBinary
 
display dialog ¬
intToBinary(5) & linefeed & ¬
intToBinary(50) & linefeed & ¬
intToBinary(9000) & linefeed</syntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 627 ⟶ 1,047:
.Ls_magic_number_10: .word 0x66666667
 
</syntaxhighlight>
</lang>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">print as.binary 5
print as.binary 50
print as.binary 9000</syntaxhighlight>
{{out}}
 
<pre>101
110010
10001100101000</pre>
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % NumberToBinary(5) ;101
MsgBox % NumberToBinary(50) ;110010
MsgBox % NumberToBinary(9000) ;10001100101000
Line 639 ⟶ 1,068:
Result := (InputNumber & 1) . Result, InputNumber >>= 1
Return, Result
}</langsyntaxhighlight>
=={{header|AutoIt}}==
<langsyntaxhighlight lang="autoit">
ConsoleWrite(IntToBin(50) & @CRLF)
 
Line 657 ⟶ 1,086:
Return $r
EndFunc ;==>IntToBin
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">BEGIN {
print tobinary(0)
print tobinary(1)
print tobinary(5)
print tobinary(50)
Line 667 ⟶ 1,098:
 
function tobinary(num) {
outstr = ""num % 2
lwhile (num = int(num / 2))
while outstr = (num l% 2) {outstr
if ( l%2 == 0 ) {
outstr = "0" outstr
} else {
outstr = "1" outstr
}
l = int(l/2)
}
# Make sure we output a zero for a value of zero
if ( outstr == "" ) {
outstr = "0"
}
return outstr
}</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="axe">Lbl BIN
.Axe supports 16-bit integers, so 16 digits are enough
L₁+16→P
Line 696 ⟶ 1,116:
End
Disp P,i
Return</langsyntaxhighlight>
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="freebasic">' Binary digits
OPTION MEMTYPE int
INPUT n$
Line 706 ⟶ 1,125:
ELSE
PRINT CHOP$(BIN$(VAL(n$)), "0", 1)
ENDIF</langsyntaxhighlight>
=={{header|Bash}}==
<syntaxhighlight lang="bash">
function to_binary () {
if [ $1 -ge 0 ]
then
val=$1
binary_digits=()
 
while [ $val -gt 0 ]; do
=={{header|Batch File}}==
bit=$((val % 2))
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.
quotient=$((val / 2))
<lang dos>@echo off
binary_digits+=("${bit}")
:num2bin IntVal [RtnVar]
val=$quotient
setlocal enableDelayedExpansion
set /a n=%~1 done
echo "${binary_digits[*]}" | rev
set rtn=
else
for /l %%b in (0,1,31) do (
set /a echo ERROR : "d=n&1,negative n>>=1number"
set rtn=!d!!rtn! exit 1
) fi
}
for /f "tokens=* delims=0" %%a in ("!rtn!") do set rtn=%%a
(endlocal & rem -- return values
if "%~2" neq "" (set %~2=%rtn%) else echo %rtn%
)
exit /b</lang>
 
array=(5 50 9000)
for number in "${array[@]}"; do
echo $number " :> " $(to_binary $number)
done
</syntaxhighlight>
{{out}}
<pre>
5 :> 1 0 1
50 :> 1 1 0 0 1 0
9000 :> 1 0 0 0 1 1 0 0 1 0 1 0 0 0
</pre>
=={{header|BASIC}}==
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic"> 0 N = 5: GOSUB 1:N = 50: GOSUB 1:N = 9000: GOSUB 1: END
1 LET N2 = ABS ( INT (N))
2 LET B$ = ""
Line 737 ⟶ 1,170:
7 NEXT N1
8 PRINT B$
9 RETURN</langsyntaxhighlight>
{{out}}
<pre>101
Line 745 ⟶ 1,178:
 
==={{header|BASIC256}}===
<langsyntaxhighlight lang="basic256">
# DecToBin.bas
# BASIC256 1.1.4.0
Line 756 ⟶ 1,189:
print a[i] + chr(9) + toRadix(a[i],2) # radix (decimal, base2)
next i
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 765 ⟶ 1,198:
 
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang="bbcbasic"> FOR num% = 0 TO 16
PRINT FN_tobase(num%, 2, 0)
NEXT
Line 780 ⟶ 1,213:
M% -= 1
UNTIL (N%=FALSE OR N%=TRUE) AND M%<=0
=A$</langsyntaxhighlight>
The above is a generic "Convert to any base" program.
Here is a faster "Convert to Binary" program:
<langsyntaxhighlight lang="bbcbasic">PRINT FNbinary(5)
PRINT FNbinary(50)
PRINT FNbinary(9000)
Line 794 ⟶ 1,227:
N% = N% >>> 1 : REM BBC Basic prior to V5 can use N% = N% DIV 2
UNTIL N% = 0
=A$</langsyntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">10 for c = 1 to 3
20 read n
30 print n;"-> ";vin$(n)
40 next c
80 end
100 sub vin$(n)
110 b$ = ""
120 n = abs(int(n))
130 '
140 b$ = str$(n mod 2)+b$
150 n = int(n/2)
160 if n > 0 then 130
170 vin$ = b$
180 end sub
200 data 5,50,9000</syntaxhighlight>
 
==={{header|Commodore BASIC}}===
Since the task only requires nonnegative integers, we use a negative one to signal the end of the demonstration data.
<lang commodorebasic>10 N = 5 : GOSUB 100
 
20 N = 50 : GOSUB 100
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.
30 N = 9000 : GOSUB 100
 
40 END
<syntaxhighlight lang="gwbasic">10 READ N
90 REM *** SUBROUTINE: CONVERT DECIMAL TO BINARY
20 IF N < 0 THEN 70
100 N2 = ABS(INT(N))
30 GOSUB 100
110 B$ = ""
40 PRINT N"-> "B$
120 FOR N1 = N2 TO 0 STEP 0
50 GOTO 10
130 : N2 = INT(N1 / 2)
60 DATA 5, 50, 9000, -1
140 : B$ = STR$(N1 - N2 * 2) + B$
70 END
150 : N1 = N2
90 REM *** SUBROUTINE: CONVERT INTEGER IN N TO BINARY STRING B$
160 NEXT N1
100 B$=""
170 PRINT B$
110 FOR N1 = ABS(INT(N)) TO 0 STEP 0
180 RETURN</lang>
120 : B$ = MID$(STR$(N1 AND 1),2) + B$
130 : N1 = INT(N1/2)
140 NEXT N1
150 RETURN</syntaxhighlight>
 
{{Out}}
<pre>
5 -> 101
50 -> 110010
9000 -> 10001100101000
</pre>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">10 PRINT BIN$(50)
100 DEF BIN$(N)
110 LET N=ABS(INT(N)):LET B$=""
Line 820 ⟶ 1,282:
150 LOOP WHILE N>0
160 LET BIN$=B$
170 END DEF</langsyntaxhighlight>
 
==={{header|QBasic}}===
<syntaxhighlight lang="qbasic">FUNCTION BIN$ (N)
N = ABS(INT(N))
B$ = ""
DO
B$ = STR$(N MOD 2) + B$
N = INT(N / 2)
LOOP WHILE N > 0
BIN$ = B$
END FUNCTION
 
fmt$ = "#### -> &"
PRINT USING fmt$; 5; BIN$(5)
PRINT USING fmt$; 50; BIN$(50)
PRINT USING fmt$; 9000; BIN$(9000)</syntaxhighlight>
 
==={{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.
<syntaxhighlight lang="tinybasic}}">REM variables:
REM A-O: binary digits with A least significant and N most significant
REM X: number whose binary expansion we want
REM Z: running value
 
INPUT X
LET Z = X
IF Z = 0 THEN GOTO 999
IF (Z/2)*2<>Z THEN LET A = 1
LET Z = (Z - A) / 2
IF (Z/2)*2<>Z THEN LET B = 1
LET Z = (Z - B) / 2
IF (Z/2)*2<>Z THEN LET C = 1
LET Z = (Z - C) / 2
IF (Z/2)*2<>Z THEN LET D = 1
LET Z = (Z - D) / 2
IF (Z/2)*2<>Z THEN LET E = 1
LET Z = (Z - E) / 2
IF (Z/2)*2<>Z THEN LET F = 1
LET Z = (Z - F) / 2
IF (Z/2)*2<>Z THEN LET G = 1
LET Z = (Z - G) / 2
IF (Z/2)*2<>Z THEN LET H = 1 REM THIS IS ALL VERY TEDIOUS
LET Z = (Z - H) / 2
IF (Z/2)*2<>Z THEN LET I = 1
LET Z = (Z - I) / 2
IF (Z/2)*2<>Z THEN LET J = 1
LET Z = (Z - J) / 2
IF (Z/2)*2<>Z THEN LET K = 1
LET Z = (Z - K) / 2
IF (Z/2)*2<>Z THEN LET L = 1
LET Z = (Z - L) / 2
IF (Z/2)*2<>Z THEN LET M = 1
LET Z = (Z - M) / 2
IF (Z/2)*2<>Z THEN LET N = 1
LET Z = (Z - N) / 2
LET O = Z
IF X >= 16384 THEN GOTO 114
IF X >= 8192 THEN GOTO 113
IF X >= 4096 THEN GOTO 112
IF X >= 2048 THEN GOTO 111
IF X >= 1024 THEN GOTO 110
IF X >= 512 THEN GOTO 109
IF X >= 256 THEN GOTO 108
IF X >= 128 THEN GOTO 107 REM THIS IS ALSO TEDIOUS
IF X >= 64 THEN GOTO 106
IF X >= 32 THEN GOTO 105
IF X >= 16 THEN GOTO 104
IF X >= 8 THEN GOTO 103
IF X >= 4 THEN GOTO 102
IF X >= 2 THEN GOTO 101
PRINT 1
END
101 PRINT B,A
END
102 PRINT C,B,A
END
103 PRINT D,C,B,A
END
104 PRINT E,D,C,B,A
END
105 PRINT F,E,D,C,B,A
END
106 PRINT G,F,E,D,C,B,A
END
107 PRINT H,G,F,E,D,C,B,A
END
108 PRINT I,H,G,D,E,D,C,B,A
END
109 PRINT J,I,H,G,F,E,D,C,B,A
END
110 PRINT K,J,I,H,G,F,E,D,C,B,A
END
111 PRINT L,K,J,I,H,G,D,E,D,C,B,A
END
112 PRINT M,L,K,J,I,H,G,F,E,D,C,B,A
END
113 PRINT N,M,L,K,J,I,H,G,F,E,D,C,B,A
END
114 PRINT O,N,M,L,K,J,I,H,G,F,E,D,C,B,A
END
 
999 PRINT 0 REM zero is the one time we DO want to print a leading zero
END</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">FUNCTION BIN$ (N)
LET N = ABS(INT(N))
LET B$ = ""
DO
LET I = MOD(N, 2)
LET B$ = STR$(I) & B$
LET N = INT(N / 2)
LOOP WHILE N > 0
LET BIN$ = B$
END FUNCTION
 
 
PRINT USING "####": 5;
PRINT " -> "; BIN$(5)
PRINT USING "####": 50;
PRINT " -> "; BIN$(50)
PRINT USING "####": 9000;
PRINT " -> "; BIN$(9000)
END</syntaxhighlight>
 
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="qbasic">PROGRAM "binardig"
VERSION "0.0000"
 
DECLARE FUNCTION Entry ()
 
FUNCTION Entry ()
DIM a[3]
a[0] = 5
a[1] = 50
a[2] = 9000
FOR i = 0 TO 2
PRINT FORMAT$ ("####", a[i]); " -> "; BIN$(a[i])
NEXT i
 
END FUNCTION
END PROGRAM</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang="dos">@echo off
:num2bin IntVal [RtnVar]
setlocal enableDelayedExpansion
set /a n=%~1
set rtn=
for /l %%b in (0,1,31) do (
set /a "d=n&1, n>>=1"
set rtn=!d!!rtn!
)
for /f "tokens=* delims=0" %%a in ("!rtn!") do set rtn=%%a
(endlocal & rem -- return values
if "%~2" neq "" (set %~2=%rtn%) else echo %rtn%
)
exit /b</syntaxhighlight>
=={{header|bc}}==
{{trans|dc}}
<langsyntaxhighlight lang="bc">obase = 2
5
50
9000
quit</langsyntaxhighlight>
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
let writebin(x) be
$( let f(x) be
$( if x>1 then f(x>>1)
wrch((x & 1) + '0')
$)
f(x)
wrch('*N')
$)
 
let start() be
$( writebin(5)
writebin(50)
writebin(9000)
$)</syntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|Beads}}==
<syntaxhighlight lang="beads">beads 1 program 'Binary Digits'
calc main_init
loop across:[5, 50, 9000] val:v
log to_str(v, base:2)</syntaxhighlight>
{{out}}
<pre>101
110010
10001100101000
</pre>
=={{header|Befunge}}==
Reads the number to convert from standard input.
<langsyntaxhighlight lang="befunge">&>0\55+\:2%68>*#<+#8\#62#%/#2:_$>:#,_$@</langsyntaxhighlight>
{{out}}
<pre>9000
10001100101000</pre>
=={{header|BQN}}==
 
A BQNcrate idiom which returns the digits as a boolean array.
<syntaxhighlight lang="bqn">Bin ← 2{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}
 
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}}==
<langsyntaxhighlight lang="bracmat"> ( dec2bin
= bit bits
. :?bits
Line 853 ⟶ 1,512:
& put$(str$(!dec ":\n" dec2bin$!dec \n\n))
)
;</langsyntaxhighlight>
{{out}}
<pre>0:
Line 869 ⟶ 1,528:
423785674235000123456789:
1011001101111010111011110101001101111000000000000110001100000100111110100010101</pre>
 
=={{header|Brainf***}}==
 
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.
 
<langsyntaxhighlight lang="bf">+[ Start with n=1 to kick off the loop
[>>++<< Set up {n 0 2} for divmod magic
[->+>- Then
Line 890 ⟶ 1,548:
<[[-]<] Zero the tape for the next iteration
++++++++++. Print a newline
[-]<+] Zero it then increment n and go again</langsyntaxhighlight>
 
=={{header|Burlesque}}==
<langsyntaxhighlight lang="burlesque">
blsq ) {5 50 9000}{2B!}m[uN
101
110010
10001100101000
</syntaxhighlight>
</lang>
 
=={{header|C}}==
===With bit level operations===
<syntaxhighlight lang="c">#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings
#define _CRT_NONSTDC_NO_DEPRECATE // enable old-gold POSIX names in MSVS
 
#include <stdio.h>
#include <stdlib.h>
 
 
char* bin2str(unsigned value, char* buffer)
{
// This algorithm is not the fastest one, but is relativelly simple.
//
// A faster algorithm would be conversion octets to strings by a lookup table.
// There is only 2**8 == 256 octets, therefore we would need only 2048 bytes
// for the lookup table. Conversion of a 64-bit integers would need 8 lookups
// instead 64 and/or/shifts of bits etc. Even more... lookups may be implemented
// with XLAT or similar CPU instruction... and AVX/SSE gives chance for SIMD.
 
const unsigned N_DIGITS = sizeof(unsigned) * 8;
unsigned mask = 1 << (N_DIGITS - 1);
char* ptr = buffer;
 
for (int i = 0; i < N_DIGITS; i++)
{
*ptr++ = '0' + !!(value & mask);
mask >>= 1;
}
*ptr = '\0';
 
// Remove leading zeros.
//
for (ptr = buffer; *ptr == '0'; ptr++)
;
 
return ptr;
}
 
 
char* bin2strNaive(unsigned value, char* buffer)
{
// This variation of the solution doesn't use bits shifting etc.
 
unsigned n, m, p;
 
n = 0;
p = 1; // p = 2 ** n
while (p <= value / 2)
{
n = n + 1;
p = p * 2;
}
 
m = 0;
while (n > 0)
{
buffer[m] = '0' + value / p;
value = value % p;
m = m + 1;
n = n - 1;
p = p / 2;
}
 
buffer[m + 1] = '\0';
return buffer;
}
 
 
int main(int argc, char* argv[])
{
const unsigned NUMBERS[] = { 5, 50, 9000 };
 
const int RADIX = 2;
char buffer[(sizeof(unsigned)*8 + 1)];
 
// Function itoa is an POSIX function, but it is not in C standard library.
// There is no big surprise that Microsoft deprecate itoa because POSIX is
// "Portable Operating System Interface for UNIX". Thus it is not a good
// idea to use _itoa instead itoa: we lost compatibility with POSIX;
// we gain nothing in MS Windows (itoa-without-underscore is not better
// than _itoa-with-underscore). The same holds for kbhit() and _kbhit() etc.
//
for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++)
{
unsigned value = NUMBERS[i];
itoa(value, buffer, RADIX);
printf("itoa: %u decimal = %s binary\n", value, buffer);
}
 
// Yeep, we can use a homemade bin2str function. Notice that C is very very
// efficient (as "hi level assembler") when bit manipulation is needed.
//
for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++)
{
unsigned value = NUMBERS[i];
printf("bin2str: %u decimal = %s binary\n", value, bin2str(value, buffer));
}
 
// Another implementation - see above.
//
for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++)
{
unsigned value = NUMBERS[i];
printf("bin2strNaive: %u decimal = %s binary\n", value, bin2strNaive(value, buffer));
}
 
return EXIT_SUCCESS;
}
</syntaxhighlight>
{{output}}
<pre>itoa: 5 decimal = 101 binary
itoa: 50 decimal = 110010 binary
itoa: 9000 decimal = 10001100101000 binary
bin2str: 5 decimal = 101 binary
bin2str: 50 decimal = 110010 binary
bin2str: 9000 decimal = 10001100101000 binary
bin2strNaive: 5 decimal = 101 binary
bin2strNaive: 50 decimal = 110010 binary
bin2strNaive: 9000 decimal = 10001100101000 binary</pre>
 
===With malloc and log10===
Converts int to a string.
<langsyntaxhighlight lang="c">#include <math.h>
#include <stdio.h>
#include <stdlib.h>
Line 928 ⟶ 1,704:
ret[bits] = '\0';
return ret;
}</langsyntaxhighlight>
 
{{out}}
Line 951 ⟶ 1,727:
10010
10011</pre>
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
 
class Program
{
static void Main()
{
foreach (var number in new[] { 5, 50, 9000 })
{
Console.WriteLine(Convert.ToString(number, 2));
}
}
}</syntaxhighlight>
Another version using dotnet 5<syntaxhighlight lang="csharp dotnet 5.0">using System;
using System.Text;
 
static string ToBinary(uint x) {
if(x == 0) return "0";
var bin = new StringBuilder();
for(uint mask = (uint)1 << (sizeof(uint)*8 - 1);mask > 0;mask = mask >> 1)
bin.Append((mask & x) > 0 ? "1" : "0");
return bin.ToString().TrimStart('0');
}
 
Console.WriteLine(ToBinary(5));
Console.WriteLine(ToBinary(50));
Console.WriteLine(ToBinary(9000));</syntaxhighlight>
{{out}}
<pre>
101
110010
10001100101000
</pre>
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <bitset>
#include <iostream>
#include <limits>
Line 975 ⟶ 1,783:
print_bin(9000);
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 984 ⟶ 1,792:
</pre>
Shorter version using bitset
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <bitset>
void printBits(int n) { // Use int like most programming languages.
Line 997 ⟶ 1,805:
printBits(50);
printBits(9000);
} // for testing with n=0 printBits<32>(0);</langsyntaxhighlight>
Using >> operator. (1st example is 2.75x longer. Matter of taste.)
<langsyntaxhighlight lang="cpp">#include <iostream>
int main(int argc, char* argv[]) {
unsigned int in[] = {5, 50, 9000}; // Use int like most programming languages
Line 1,007 ⟶ 1,815:
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.
<langsyntaxhighlight lang="cpp">#include <iostream>
int main(int argc, char* argv[]) { // Usage: program.exe 5 50 9000
for (int i = 1; i < argc; i++) // argv[0] is program name
Line 1,016 ⟶ 1,824:
std::cout << ('0' + b & 1) << (!at ? "\n": ""); // '0' or '1'. Add EOL if last bit of num
}
</syntaxhighlight>
</lang>
Using bitwise operations with recursion.
<langsyntaxhighlight lang="cpp">
#include <iostream>
 
Line 1,030 ⟶ 1,838:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,037 ⟶ 1,845:
10001100101000
</pre>
 
=={{header|C sharp|C#}}==
<lang csharp>using System;
 
class Program
{
static void Main()
{
foreach (var number in new[] { 5, 50, 9000 })
{
Console.WriteLine(Convert.ToString(number, 2));
}
}
}</lang>
{{out}}
<pre>
101
110010
10001100101000
</pre>
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon"> shared void run() {
void printBinary(Integer integer) =>
Line 1,067 ⟶ 1,854:
printBinary(50);
printBinary(9k);
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(Integer/toBinaryString 5)
(Integer/toBinaryString 50)
(Integer/toBinaryString 9000)</langsyntaxhighlight>
=={{header|CLU}}==
<syntaxhighlight lang="clu">binary = proc (n: int) returns (string)
bin: string := ""
while n > 0 do
bin := string$c2s(char$i2c(48 + n // 2)) || bin
n := n / 2
end
return(bin)
end binary
 
start_up = proc ()
po: stream := stream$primary_output()
tests: array[int] := array[int]$[5, 50, 9000]
for test: int in array[int]$elements(tests) do
stream$putl(po, int$unparse(test) || " -> " || binary(test))
end
end start_up</syntaxhighlight>
{{out}}
<pre>5 -> 101
50 -> 110010
9000 -> 10001100101000</pre>
=={{header|COBOL}}==
<langsyntaxhighlight COBOLlang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. SAMPLE.
 
Line 1,101 ⟶ 1,908:
display binary_number
stop run.
</syntaxhighlight>
</lang>
Free-form, using a reference modifier to index into binary-number.
<langsyntaxhighlight lang="cobol">IDENTIFICATION DIVISION.
PROGRAM-ID. binary-conversion.
 
Line 1,129 ⟶ 1,936:
end-perform.
display binary-number.
stop run.</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">binary = (n) ->
new Number(n).toString(2)
console.log binary n for n in [5, 50, 9000]</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Just print the number with "~b":
<langsyntaxhighlight lang="lisp">(format t "~b" 5)
 
; or
 
(write 5 :base 2)</langsyntaxhighlight>
 
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE BinaryDigits;
IMPORT StdLog,Strings;
Line 1,163 ⟶ 1,967:
END Do;
END BinaryDigits.
</syntaxhighlight>
</lang>
Execute: ^Q BinaryDigits.Do <br/>
{{out}}
Line 1,170 ⟶ 1,974:
50:> 110010
9000:> 10001100101000</pre>
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
 
sub print_binary(n: uint32) is
var buffer: uint8[33];
var p := &buffer[32];
[p] := 0;
while n != 0 loop
p := @prev p;
[p] := ((n as uint8) & 1) + '0';
n := n >> 1;
end loop;
print(p);
print_nl();
end sub;
 
print_binary(5);
print_binary(50);
print_binary(9000);</syntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|Crystal}}==
{{trans|Ruby}}
Using an array
<langsyntaxhighlight lang="ruby">[5,50,9000].each do |n|
puts "%b" % n
end</langsyntaxhighlight>
Using a tuple
<langsyntaxhighlight lang="ruby">{5,50,9000}.each { |n| puts n.to_s(2) }</langsyntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio;
 
foreach (immutable i; 0 .. 16)
writefln("%b", i);
}</langsyntaxhighlight>
{{out}}
<pre>0
Line 1,208 ⟶ 2,035:
1110
1111</pre>
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">String binary(int n) {
if(n<0)
throw new IllegalArgumentException("negative numbers require 2s complement");
Line 1,234 ⟶ 2,060:
// fails due to precision limit
print(binary(0x123456789abcdef));
}</langsyntaxhighlight>
 
=={{header|dc}}==
<syntaxhighlight lang ="dc">2o 5p 50p 9000p</langsyntaxhighlight>
 
{{out}}
Line 1,243 ⟶ 2,068:
110010
10001100101000</pre>
 
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
<lang Delphi>
program BinaryDigit;
{$APPTYPE CONSOLE}
Line 1,264 ⟶ 2,088:
writeln(' 50: ',IntToBinStr(50));
writeln('9000: '+IntToBinStr(9000));
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,272 ⟶ 2,096:
</pre>
 
=={{header|EchoLispDraco}}==
<syntaxhighlight lang="draco">proc main() void:
<lang scheme>
writeln(5:b);
;; primitive : (number->string number [base]) - default base = 10
writeln(50:b);
writeln(9000:b);
corp</syntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
 
=={{header|dt}}==
(number->string 2 2)
<syntaxhighlight lang="dt">[dup 1 gt? [dup 2 % swap 2 / loop] swap do?] \loop def
→ 10
 
[\loop doin rev \to-string map "" join] \bin def
(for-each (compose writeln (rcurry number->string 2)) '( 5 50 9000)) →
 
101
[0 1 2 5 50 9000] \bin map " " join pl</syntaxhighlight>
110010
{{out}}
10001100101000
<pre>0 1 10 101 110010 10001100101000</pre>
</lang>
 
=={{header|Dyalect}}==
 
A default <code>toStringToString</code> method of type <code>Integer</code> is overridenoverridden and returns a binary representation of a number:
 
<langsyntaxhighlight lang="dyalect">func Integer.toStringToString() {
var s = ""
for x in 31^-1..0 {
if this &&& (1 <<< x) != 0 {
s += "1"
} else if s != "" {
Line 1,300 ⟶ 2,131:
s
}
 
print("5 == \(5), 50 = \(50), 1000 = \(9000)")</langsyntaxhighlight>
 
{{out}}
 
<pre>5 == 101, 50 = 110010, 1000 = 10001100101000</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
 
<lang>func$ to2bin n . r$num .
if nb$ >= 0""
while callnum to2> n / 2 r$1
if n b$ = num mod 2 =& 0b$
r$num &= "0"num div 2
else.
return num & rb$ &= "1"
.
else
r$ = ""
.
.
func pr2 n . .
call to2 n r$
if r$ = ""
print "0"
else
print r$
.
.
callprint pr2bin 5
callprint pr2bin 50
callprint pr2bin 9000</lang>
</syntaxhighlight>
 
{{out}}
<pre>
101
110010
10001100101000
</pre>
 
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">
;; primitive : (number->string number [base]) - default base = 10
 
(number->string 2 2)
→ 10
 
(for-each (compose writeln (rcurry number->string 2)) '( 5 50 9000)) →
101
110010
10001100101000
</syntaxhighlight>
 
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module BinaryDigits {
@Inject Console console;
void run() {
Int64[] tests = [0, 1, 5, 50, 9000];
 
Int longestInt = tests.map(n -> n.estimateStringLength())
.reduce(0, (max, len) -> max.notLessThan(len));
Int longestBin = tests.map(n -> (64-n.leadingZeroCount).notLessThan(1))
.reduce(0, (max, len) -> max.maxOf(len));
 
function String(Int64) num = n -> {
Int indent = longestInt - n.estimateStringLength();
return $"{' ' * indent}{n}";
};
 
function String(Int64) bin = n -> {
Int index = n.leadingZeroCount.minOf(63);
Int indent = index - (64 - longestBin);
val bits = n.toBitArray()[index ..< 64];
return $"{' ' * indent}{bits.toString().substring(2)}";
};
 
for (Int64 test : tests) {
console.print($"The decimal value {num(test)} should produce an output of {bin(test)}");
}
}
}
</syntaxhighlight>
 
{{out}}
<pre>
The decimal value 0 should produce an output of 0
The decimal value 1 should produce an output of 1
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
</pre>
 
=={{header|Elena}}==
ELENA 46.1x :
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
 
public program()
{
new int[]::({5,50,9000)}.forEach::(n)
{
console.printLine(n.toString(2))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,360 ⟶ 2,231:
=={{header|Elixir}}==
Use <code>Integer.to_string</code> with a base of 2:
<syntaxhighlight lang="elixir">
<lang Elixir>
IO.puts Integer.to_string(5, 2)
</syntaxhighlight>
</lang>
Or, using the pipe operator:
<syntaxhighlight lang="elixir">
<lang Elixir>
5 |> Integer.to_string(2) |> IO.puts
</syntaxhighlight>
</lang>
<syntaxhighlight lang="elixir">
<lang Elixir>
[5,50,9000] |> Enum.each(fn n -> IO.puts Integer.to_string(n, 2) end)
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,377 ⟶ 2,248:
10001100101000
</pre>
With Enum.map/2
<syntaxhighlight lang="elixir">
Enum.map([5, 50, 9000], fn n -> IO.puts Integer.to_string(n, 2) end)
</syntaxhighlight>
 
{{out}}
<pre>
101
110010
10001100101000
</pre>
With list comprehension
<syntaxhighlight lang="elixir">
for n <- [5, 50, 9000] do IO.puts Integer.to_string(n, 2) end
</syntaxhighlight>
 
{{out}}
<pre>
101
110010
10001100101000
</pre>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">
(defun int-to-binary (val)
(let ((x val) (result ""))
(while (> x 0)
(setq result (concat (number-to-string (% x 2)) result))
(setq x (/ x 2)))
result))
 
(message "5 => %s" (int-to-binary 5))
(message "50 => %s" (int-to-binary 50))
(message "9000 => %s" (int-to-binary 9000))
</syntaxhighlight>
{{out}}
<pre>
5 => 101
50 => 110010
9000 => 10001100101000
</pre>
 
=={{header|Epoxy}}==
<syntaxhighlight lang="epoxy">fn bin(a,b:true)
var c:""
while a>0 do
c,a:tostring(a%2)+c,bit.rshift(a,1)
cls
if b then
c:string.repeat("0",16-#c)+c
cls
return c
cls
 
var List: [5,50,9000]
 
iter Value of List do
log(Value+": "+bin(Value,false))
cls</syntaxhighlight>
{{out}}
<pre>
5: 101
50: 110010
9000: 10001100101000
</pre>
=={{header|Erlang}}==
With lists:map/2
<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}}
<pre>101
110010
10001100101000</pre>
With list comprehension
<syntaxhighlight lang="erlang">[io:fwrite("~.2B~n", [N]) || N <- [5, 50, 9000]].</syntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
With list comprehension and integer_to_list/2
<syntaxhighlight lang="erlang">[io:fwrite("~s~n", [integer_to_list(N, 2)]) || N <- [5, 50, 9000]].</syntaxhighlight>
{{out}}
<pre>101
Line 1,386 ⟶ 2,335:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function toBinary(integer i)
sequence s
s = {}
Line 1,398 ⟶ 2,347:
puts(1, toBinary(5) & '\n')
puts(1, toBinary(50) & '\n')
puts(1, toBinary(9000) & '\n')</langsyntaxhighlight>
 
=== Functional/Recursive ===
<langsyntaxhighlight lang="euphoria">include std/math.e
include std/convert.e
 
Line 1,416 ⟶ 2,365:
printf(1, "%d\n", Bin(5))
printf(1, "%d\n", Bin(50))
printf(1, "%d\n", Bin(9000))</langsyntaxhighlight>
 
=={{header|F Sharp|F#}}==
By translating C#'s approach, using imperative coding style (inflexible):
<langsyntaxhighlight FSharplang="fsharp">open System
for i in [5; 50; 9000] do printfn "%s" <| Convert.ToString (i, 2)</langsyntaxhighlight>
 
Alternatively, by creating a function <code>printBin</code> which prints in binary (more flexible):
<langsyntaxhighlight FSharplang="fsharp">open System
 
// define the function
Line 1,433 ⟶ 2,381:
// use the function
[5; 50; 9000]
|> List.iter printBin</langsyntaxhighlight>
 
Or more idiomatic so that you can use it with any printf-style function and the <code>%a</code> format specifier (most flexible):
 
<langsyntaxhighlight FSharplang="fsharp">open System
open System.IO
 
Line 1,446 ⟶ 2,394:
// use it with printfn with %a
[5; 50; 9000]
|> List.iter (printfn "binary: %a" bin)</langsyntaxhighlight>
Output (either version):
<pre>
Line 1,453 ⟶ 2,401:
10001100101000
</pre>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: io kernel math math.parser ;
 
5 >bin print
50 >bin print
9000 >bin print</langsyntaxhighlight>
=={{header|FALSE}}==
<syntaxhighlight lang="false">[0\10\[$1&'0+\2/$][]#%[$][,]#%]b:
 
5 b;!
50 b;!
9000 b;!</syntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|FBSL}}==
<langsyntaxhighlight lang="fbsl">#AppType Console
function Bin(byval n as integer, byval s as string = "") as string
if n > 0 then return Bin(n \ 2, (n mod 2) & s)
Line 1,474 ⟶ 2,430:
 
pause
</syntaxhighlight>
</lang>
=={{header|FOCAL}}==
<syntaxhighlight lang="focal">01.10 S A=5;D 2
01.20 S A=50;D 2
01.30 S A=9000;D 2
01.40 Q
 
02.10 S BX=0
02.20 S BD(BX)=A-FITR(A/2)*2
02.25 S A=FITR(A/2)
02.30 S BX=BX+1
02.35 I (-A)2.2
02.40 S BX=BX-1
02.45 D 2.6
02.50 I (-BX)2.4;T !;R
02.60 I (-BD(BX))2.7;T "0";R
02.70 T "1"</syntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">\ Forth uses a system variable 'BASE' for number conversion
 
\ HEX is a standard word to change the value of base to 16
Line 1,484 ⟶ 2,459:
\ we can easily compile a word into the system to set 'BASE' to 2
 
: binary 2 base ! ; ok
 
 
\ interactive console test with conversion and binary masking example
 
hex 0FF binary . 11111111 okcr
decimal 679 binary . 1010100111 okcr
ok
binary 11111111111 00000110000 and . 110000 ok
 
binary 11111111111 00000110000 and . cr
decimal ok
 
decimal
</lang>
 
</syntaxhighlight>
 
{{out}}
 
<pre>
11111111
1010100111
110000
</pre>
=={{header|Fortran}}==
Please find compilation instructions and the example run at the start of the FORTRAN90 source that follows. Thank you.
<syntaxhighlight lang="fortran">
<lang FORTRAN>
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sun May 19 23:14:14
Line 1,558 ⟶ 2,540:
 
end program bits
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<lang freebasic>
' FreeBASIC v1.05.0 win64
Dim As String fmt = "#### -> &"
Print Using fmt; 5; Bin(5)
Print Using fmt; 50; Bin(50)
Print Using fmt; 9000; Bin(9000)
Print
Print "Press any key to exit the program"
Sleep
End
</lang>
 
{{out}}
<pre>
5 -> 101
50 -> 110010
9000 -> 10001100101000
</pre>
 
=={{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>.
The <tt>system</tt> unit is automatically included by ''every'' program and is guaranteed to work on every supported platform.
<langsyntaxhighlight lang="pascal">program binaryDigits(input, output, stdErr);
{$mode ISO}
 
Line 1,605 ⟶ 2,566:
writeLn(binaryNumber(50));
writeLn(binaryNumber(9000));
end.</langsyntaxhighlight>
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}}==
<syntaxhighlight lang="freebasic">
' FreeBASIC v1.05.0 win64
Dim As String fmt = "#### -> &"
Print Using fmt; 5; Bin(5)
Print Using fmt; 50; Bin(50)
Print Using fmt; 9000; Bin(9000)
Print
Print "Press any key to exit the program"
Sleep
End
</syntaxhighlight>
 
{{out}}
<pre>
5 -> 101
50 -> 110010
9000 -> 10001100101000
</pre>
=={{header|Frink}}==
The following all provide equivalent output. Input can be arbitrarily-large integers.
<langsyntaxhighlight lang="frink">
9000 -> binary
9000 -> base2
base2[9000]
base[9000, 2]
</syntaxhighlight>
</lang>
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">for n <- [5, 50, 9000, 9000000000]
println( n, bin(n) )</langsyntaxhighlight>
 
{{out}}
Line 1,629 ⟶ 2,607:
9000000000, 1000011000011100010001101000000000
</pre>
 
=={{header|Futhark}}==
 
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.
 
<syntaxhighlight lang="futhark">
<lang Futhark>
fun main(x: i32): i64 =
loop (out = 0i64) = for i < 32 do
Line 1,641 ⟶ 2,618:
in out
in out
</syntaxhighlight>
</lang>
=={{header|FutureBasic}}==
The decimal to binary conversion can be handled with a simple function.
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
local fn IntegerToBinaryStr( x as NSInteger ) as CFStringRef
CFStringRef resultStr : resultStr = @""
while ( x )
resultStr = fn StringByAppendingString( fn StringWithFormat( @"%lu", x && 1 ), resultStr )
x = x >> 1
wend
end fn = resultStr
 
NSLog( @" 5 = %@", fn IntegerToBinaryStr( 5 ) )
NSLog( @" 50 = %@", fn IntegerToBinaryStr( 50 ) )
NSLog( @"9000 = %@", fn IntegerToBinaryStr( 9000 ) )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
5 = 101
50 = 110010
9000 = 10001100101000
</pre>
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=03e84768e6ee2af9b7664efa04fa6da8 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim siBin As Short[] = [5, 50, 9000]
Dim siCount As Short
Line 1,653 ⟶ 2,655:
Next
 
End</langsyntaxhighlight>
{{out}}
<pre>
Line 1,660 ⟶ 2,662:
10001100101000
</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,672 ⟶ 2,673:
fmt.Printf("%b\n", i)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,692 ⟶ 2,693:
1111
</pre>
 
=={{header|Groovy}}==
Solutions:
<langsyntaxhighlight lang="groovy">print '''
n binary
----- ---------------
Line 1,701 ⟶ 2,701:
[5, 50, 9000].each {
printf('%5d %15s\n', it, Integer.toBinaryString(it))
}</langsyntaxhighlight>
{{out}}
<pre> n binary
Line 1,708 ⟶ 2,708:
50 110010
9000 10001100101000</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List
import Numeric
import Text.Printf
 
-- Use the built-in function showBin.
toBin n = showBin n ""
 
-- Use the built-in function showIntAtBase.
Line 1,733 ⟶ 2,735:
main = do
putStrLn $ printf "%4s %14s %14s" "N" "toBin" "toBin1"
mapM_ printToBin [5, 50, 9000]</langsyntaxhighlight>
{{out}}
<pre>
Line 1,741 ⟶ 2,743:
9000 10001100101000 10001100101000
</pre>
 
 
and in terms of first and swap, we could also write this as:
 
<syntaxhighlight lang="haskell">import Data.Bifunctor (first)
import Data.List (unfoldr)
import Data.Tuple (swap)
 
---------------------- BINARY DIGITS ---------------------
 
binaryDigits :: Int -> String
binaryDigits = reverse . unfoldr go
where
go 0 = Nothing
go n = Just . first ("01" !!) . swap . quotRem n $ 2
 
 
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_
( putStrLn
. ( ((<>) . (<> " -> ") . show)
<*> binaryDigits
)
)
[5, 50, 9000]</syntaxhighlight>
{{Out}}
<pre>5 -> 101
50 -> 110010
9000 -> 10001100101000</pre>
 
=={{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.
<langsyntaxhighlight Iconlang="icon">procedure main()
every i := 5 | 50 | 255 | 1285 | 9000 do
write(i," = ",binary(i))
Line 1,766 ⟶ 2,799:
}
return reverse(trim(b,"0")) # nothing extraneous
end</langsyntaxhighlight>
{{out}}
<pre>5 = 101
Line 1,773 ⟶ 2,806:
1285 = 10100000101
9000 = 10001100101000</pre>
 
 
=={{header|Idris}}==
<langsyntaxhighlight Idrislang="idris">module Main
 
binaryDigit : Integer -> Char
Line 1,794 ⟶ 2,825:
putStrLn (binaryString 50)
putStrLn (binaryString 9000)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,802 ⟶ 2,833:
10001100101000
</pre>
 
=={{header|J}}==
Generate a list of binary digits and use it to select characters from string '01'.
<lang j> tobin=: -.&' '@":@#:
<syntaxhighlight lang="j"> tobin=: '01'{~#:
tobin 5
101
Line 1,810 ⟶ 2,841:
110010
tobin 9000
10001100101000</langsyntaxhighlight>
Uses implicit output.
Algorithm: Remove spaces from the character list which results from formatting the binary list which represents the numeric argument.
 
I am using implicit output.
 
=={{header|Java}}==
<p>
<lang java>public class Main {
The <code>Integer</code> class offers the <code>toBinaryString</code> method.
public static void main(String[] args) {
</p>
System.out.println(Integer.toBinaryString(5));
<syntaxhighlight lang="java">
System.out.println(Integer.toBinaryString(50));
System.out.println(Integer.toBinaryString(9000)5);
</syntaxhighlight>
}
<syntaxhighlight lang="java">
}</lang>
Integer.toBinaryString(50);
{{out}}
</syntaxhighlight>
<pre>101
<syntaxhighlight lang="java">
Integer.toBinaryString(9000);
</syntaxhighlight>
<p>
If you printed these values you would get the following.
</p>
<pre>
101
110010
10001100101000</pre>
</pre>
 
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight lang="javascript">function toBinary(number) {
return new Number(number)
.toString(2);
Line 1,838 ⟶ 2,876:
// alert() in a browser, wscript.echo in WSH, etc.
print(toBinary(demoValues[i]));
}</langsyntaxhighlight>
 
===ES6===
The simplest showBinshowBinary (or showIntAtBase), using default digit characters, would use JavaScript's standard String.toString(base):
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
"use strict";
 
// ------------------ BINARY DIGITS ------------------
// showIntAtBase_ :: // Int -> Int -> String
const showIntAtBase_ = (base, n) => (n)
.toString(base);
 
// showBinshowBinary :: Int -> String
const showBinshowBinary = n => showIntAtBase_(2, n);
showIntAtBase_(2)(n);
 
// GENERIC FUNCTIONS FOR TEST ---------------------------------------------
 
// intercalateshowIntAtBase_ :: String// Int -> [a]Int -> String
const intercalateshowIntAtBase_ = (s, xs)base => xs.join(s);
n => n.toString(base);
 
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
 
// ---------------------- TEST -----------------------
// unlines :: [String] -> String
const unlinesmain = xs() => xs.join('\n');[5, 50, 9000]
.map(n => `${n} -> ${showBinary(n)}`)
.join("\n");
 
// show :: a -> String
const show = x => JSON.stringify(x);
 
// MAIN ---
// TEST -------------------------------------------------------------------
return main();
 
})();</syntaxhighlight>
return unlines(map(
n => intercalate(' -> ', [show(n), showBin(n)]),
[5, 50, 9000]
));
})();</lang>
{{Out}}
<pre>5 -> 101
Line 1,880 ⟶ 2,912:
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:
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
"use strict";
 
// -------------- DIGITS FOR GIVEN BASE --------------
// showBin :: Int -> String
const showBin = n => {
const binaryChar = n => n !== 0 ? '一' : '〇';
 
// showIntAtBase :: Int -> (Int -> Char) ->
return showIntAtBase(2, binaryChar, n, '');
// Int -> String -> String
};
const showIntAtBase = base =>
// A string representation of n, in the given base,
// using a supplied (Int -> Char) function for digits,
// and a supplied suffix string.
toChr => n => rs => {
const go = ([x, d], r) => {
const r_ = toChr(d) + r;
 
// showIntAtBase :: Int -> (Int -> Char) -> Int -> String ->return String0 !== x ? (
go(quotRem(x)(base), r_)
const showIntAtBase = (base, toChr, n, rs) => {
const showIt = ([n, d], r ) =>: {r_;
const r_ = toChr(d) + r};
return n !== 0 ? (
showIt(quotRem(n, base), r_)
) : r_;
};
return base <= 1 ? (
'error: showIntAtBase applied to unsupported base'
) : n < 0 ? (
'error: showIntAtBase applied to negative number'
) : showIt(quotRem(n, base), rs);
};
 
const e = "error: showIntAtBase applied to";
// quotRem :: Integral a => a -> a -> (a, a)
const quotRem = (m, n) => [Math.floor(m / n), m % n];
 
return 1 >= base ? (
// GENERIC FUNCTIONS FOR TEST ---------------------------------------------
`${e} unsupported base`
) : 0 > n ? (
`${e} negative number`
) : go(quotRem(n)(base), rs);
};
 
// ---------------------- TEST -----------------------
// intercalate :: String -> [a] -> String
const intercalatemain = (s, xs) => xs.join(s);{
// showHanBinary :: Int -> String
const showHanBinary = n =>
showIntAtBase(2)(
x => "〇一" [x]
)(n)("");
 
// map :: (a -> b) ->return [a]5, ->50, [b9000]
const map = (f, xs) => xs .map(f);
n => `${n} -> ${showHanBinary(n)}`
)
.join("\n");
};
 
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
 
// --------------------- GENERIC ---------------------
// show :: a -> String
const show = x => JSON.stringify(x);
 
// quotRem :: Integral a => a -> a -> (a, a)
// TEST -------------------------------------------------------------------
const quotRem = m =>
// The quotient, tupled with the remainder.
n => [Math.trunc(m / n), m % n];
 
 
return unlines(map(
// MAIN ---
n => intercalate(' -> ', [show(n), showBin(n)]), [5, 50, 9000]
)return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>5 -> 一〇一
50 -> 一一〇〇一〇
9000 -> 一〇〇〇一一〇〇一〇一〇〇〇</pre>
 
=={{header|Joy}}==
<syntaxhighlight lang="joy">DEFINE bin == "" [pop 1 >] [[2 div "01" of] dip cons] while ["01" of] dip cons.
<lang joy>HIDE
 
_ == [null] [pop] [2 div swap] [48 + putch] linrec
[0 1 2 5 50 9000] [bin] map put.</syntaxhighlight>
IN
{{out}}
int2bin == [null] [48 + putch] [_] ifte '\n putch
<pre>["0" "1" "10" "101" "110010" "10001100101000"]</pre>
END</lang>
 
Using int2bin:
<lang joy>0 setautoput
0 int2bin
5 int2bin
50 int2bin
9000 int2bin.</lang>
=={{header|jq}}==
<langsyntaxhighlight lang="jq">def binary_digits:
[ recurse( ./2 | floor; . > 0) % 2 ] | reverse | join("") ;
if . == 0 then "0"
else [recurse( if . == 0 then empty else ./2 | floor end ) % 2 | tostring]
| reverse
| .[1:] # remove the leading 0
| join("")
end ;
 
# The task:
(5, 50, 9000) | binary_digits</langsyntaxhighlight>
{{Out}}
$ jq -n -r -f Binary_digits.jq
Line 1,960 ⟶ 2,990:
110010
10001100101000
 
=={{header|Julia}}==
{{works with|Julia|1.0}}
 
<langsyntaxhighlight lang="julia">using Printf
 
for n in (0, 5, 50, 9000)
Line 1,974 ⟶ 3,003:
for n in (0, 5, 50, 9000)
@printf("%6i → %s\n", n, string(n, base=2, pad=20))
end</langsyntaxhighlight>
 
{{out}}
Line 1,987 ⟶ 3,016:
50 → 00000000000000110010
9000 → 00000010001100101000</pre>
 
=={{header|K}}==
<langsyntaxhighlight lang="k"> tobin: ,/$2_vs
tobin' 5 50 9000
("101"
"110010"
"10001100101000")</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">
<lang scala>// version 1.0.5-2
fun main() {
 
fun main(args: Array<String>) {
val numbers = intArrayOf(5, 50, 9000)
numbers.forEach { println("$it -> ${it.toString(2)}") }
for (number in numbers) println("%4d".format(number) + " -> " + Integer.toBinaryString(number))
}</langsyntaxhighlight>
 
{{out}}
<pre>
5 -> 101
50 -> 110010
9000 -> 10001100101000
</pre>
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">function bin {
typeset -i2 n=$1
print -r -- "${n#2#}"
}
 
print -r -- $(for i in 0 1 2 5 50 9000; do bin "$i"; done)</syntaxhighlight>
{{out}}
<pre>0 1 10 101 110010 10001100101000</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def dec2bin
{lambda {:dec}
{if {= :dec 0}
then 0
else {if {< :dec 2}
then 1
else {dec2bin {floor {/ :dec 2}}}{% :dec 2} }}}}
-> dec2bin
 
{dec2bin 5} -> 101
{dec2bin 5} -> 110010
{dec2bin 9000} -> 10001100101000
 
{S.map dec2bin 5 50 9000}
-> 101 110010 10001100101000
 
{S.map {lambda {:i} {br}:i -> {dec2bin :i}} 5 50 9000}
->
5 -> 101
50 -> 110010
9000 -> 10001100101000
</syntaxhighlight>
 
As a (faster) alternative we can ask some help from Javascript who knows how to do:
 
<syntaxhighlight lang="scheme">
1) we add to the lambdatalk's dictionary the Javascript primitive "dec2bin"
{script
LAMBDATALK.DICT["dec2bin"] = function() {
return Number( arguments[0].trim() ).toString(2)
};
}
 
2) we use it in the wiki page:
'{S.map dec2bin 5 50 9000}
-> 101 110010 10001100101000
}
</syntaxhighlight>
 
=={{header|Lang}}==
<syntaxhighlight lang="lang">
fn.println(fn.toTextBase(5, 2))
fn.println(fn.toTextBase(50, 2))
fn.println(fn.toTextBase(9000, 2))
</syntaxhighlight>
 
=={{header|Lang5}}==
<langsyntaxhighlight lang="lang5">'%b '__number_format set
[5 50 9000] [3 1] reshape .</langsyntaxhighlight>
{{out}}
<pre>[
Line 2,019 ⟶ 3,103:
[ 10001100101000 ]
]</pre>
 
=={{header|LFE}}==
 
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:
<langsyntaxhighlight lang="lisp">
(: 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:
<langsyntaxhighlight lang="lisp">
(: lists foreach
(lambda (x)
Line 2,035 ⟶ 3,118:
(list (: erlang integer_to_list x 2))))
(list 5 50 9000))
</syntaxhighlight>
</lang>
{{out|note=for both examples}}
<pre>
Line 2,042 ⟶ 3,125:
10001100101000
</pre>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">for a = 0 to 16
print a;"=";dec2bin$(a)
next
Line 2,059 ⟶ 3,141:
wend
end function
</syntaxhighlight>
</lang>
=={{header|Little Man Computer}}==
Runs in a home-made simulator, which is compatible with Peter Higginson's online simulator except that it has more room for output. Makes use of PH's non-standard OTC instruction to output ASCII characters.
 
The maximum integer in LMC is 999, so 90000 in the task is here replaced by 900.
<syntaxhighlight lang="little man computer">
// Little Man Computer, for Rosetta Code.
// Read numbers from user and display them in binary.
// Exit when input = 0.
input INP
BRZ zero
STA N
// Write number followed by '->'
OUT
LDA asc_hy
OTC
LDA asc_gt
OTC
// Find greatest power of 2 not exceeding N,
// and count how many digits will be output
LDA c1
STA pwr2
loop STA nrDigits
LDA N
SUB pwr2
SUB pwr2
BRP double
BRA part2 // jump out if next power of 2 would exceed N
double LDA pwr2
ADD pwr2
STA pwr2
LDA nrDigits
ADD c1
BRA loop
// Write the binary digits
part2 LDA N
SUB pwr2
set_diff STA diff
LDA asc_1 // first digit is always 1
wr_digit OTC // write digit
LDA nrDigits // count down the number of digits
SUB c1
BRZ input // if all digits done, loop for next number
STA nrDigits
// We now want to compare diff with pwr2/2.
// Since division is awkward in LMC, we compare 2*diff with pwr2.
LDA diff // diff := diff * 2
ADD diff
STA diff
SUB pwr2 // is diff >= pwr2 ?
BRP set_diff // yes, update diff and write '1'
LDA asc_0 // no, write '0'
BRA wr_digit
zero HLT // stop if input = 0
// Constants
c1 DAT 1
asc_hy DAT 45
asc_gt DAT 62
asc_0 DAT 48
asc_1 DAT 49
// Variables
N DAT
pwr2 DAT
nrDigits DAT
diff DAT
</syntaxhighlight>
{{out}}
<pre>
5->101
50->110010
900->1110000100
</pre>
=={{header|LLVM}}==
{{trans|C}}
<langsyntaxhighlight lang="llvm">; ModuleID = 'binary.c'
; source_filename = "binary.c"
; target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
Line 2,242 ⟶ 3,394:
!0 = !{i32 1, !"wchar_size", i32 2}
!1 = !{i32 7, !"PIC Level", i32 2}
!2 = !{!"clang version 6.0.1 (tags/RELEASE_601/final)"}</langsyntaxhighlight>
{{out}}
<pre>0
Line 2,264 ⟶ 3,416:
10010
10011</pre>
 
=={{header|Locomotive Basic}}==
<langsyntaxhighlight lang="locobasic">10 PRINT BIN$(5)
20 PRINT BIN$(50)
30 PRINT BIN$(9000)</langsyntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
 
=={{header|LOLCODE}}==
<langsyntaxhighlight LOLCODElang="lolcode">HAI 1.3
HOW IZ I DECIMULBINUR YR DECIMUL
I HAS A BINUR ITZ ""
Line 2,290 ⟶ 3,440:
VISIBLE I IZ DECIMULBINUR YR 50 MKAY
VISIBLE I IZ DECIMULBINUR YR 9000 MKAY
KTHXBYE</langsyntaxhighlight>
 
{{out}}
Line 2,298 ⟶ 3,448:
 
=={{header|Lua}}==
===Lua - Iterative===
<lang Lua>function dec2bin (n)
<syntaxhighlight lang="lua">function dec2bin(n)
local bin = ""
while n > 01 do
bin = n % 2 .. bin
n = math.floor(n / 2)
end
return n .. bin
end
 
print(dec2bin(5))
print(dec2bin(50))
print(dec2bin(9000))</langsyntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
 
===Lua - Recursive===
{{works with|Lua|5.3+}}
<syntaxhighlight lang="lua">-- for Lua 5.1/5.2 use math.floor(n/2) instead of n>>1, and n%2 instead of n&1
 
function dec2bin(n)
return n>1 and dec2bin(n>>1)..(n&1) or n
end
 
print(dec2bin(5))
print(dec2bin(50))
print(dec2bin(9000))</syntaxhighlight>
{{out}}
<pre>101
Line 2,316 ⟶ 3,483:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Form 90, 40
Line 2,370 ⟶ 3,537:
}
Checkit
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 2,384 ⟶ 3,551:
 
</pre >
=={{header|MACRO-11}}==
<syntaxhighlight lang="macro11"> .TITLE BINARY
.MCALL .TTYOUT,.EXIT
BINARY::MOV #3$,R5
BR 2$
1$: JSR PC,PRBIN
2$: MOV (R5)+,R0
BNE 1$
.EXIT
3$: .WORD ^D5, ^D50, ^D9000, 0
 
; PRINT R0 AS BINARY WITH NEWLINE
PRBIN: MOV #3$,R1
1$: MOV #'0,R2
ROR R0
ADC R2
MOVB R2,(R1)+
TST R0
BNE 1$
2$: MOVB -(R1),R0
.TTYOUT
BNE 2$
RTS PC
.BYTE 0,0,12,15
3$: .BLKB 16 ; BUFFER
.END BINARY</syntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
 
=={{header|MAD}}==
MAD has basically no support for runtime generation of strings.
Therefore, this program works by calculating an integer whose decimal representation
matches the binary representation of the input, e.g. <code>BINARY.(5)</code> is <code>101</code>.
 
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER
INTERNAL FUNCTION(NUM)
ENTRY TO BINARY.
BTEMP = NUM
BRSLT = 0
BDIGIT = 1
BIT WHENEVER BTEMP.NE.0
BRSLT = BRSLT + BDIGIT * (BTEMP-BTEMP/2*2)
BTEMP = BTEMP/2
BDIGIT = BDIGIT * 10
TRANSFER TO BIT
END OF CONDITIONAL
FUNCTION RETURN BRSLT
END OF FUNCTION
THROUGH SHOW, FOR VALUES OF N = 5, 50, 9000
SHOW PRINT FORMAT FMT, N, BINARY.(N)
 
VECTOR VALUES FMT = $I4,2H: ,I16*$
END OF PROGRAM </syntaxhighlight>
{{out}}
<pre> 5: 101
50: 110010
9000: 10001100101000</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
> convert( 50, 'binary' );
110010
> convert( 9000, 'binary' );
10001100101000
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">StringJoin @@ ToString /@ IntegerDigits[50, 2] </langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight Matlablang="matlab"> dec2bin(5)
dec2bin(50)
dec2bin(9000) </langsyntaxhighlight>
The output is a string containing ascii(48) (i.e. '0') and ascii(49) (i.e. '1').
=={{header|Maxima}}==
 
<syntaxhighlight lang="maxima">digits([arg]) := block(
[n: first(arg), b: if length(arg) > 1 then second(arg) else 10, v: [ ], q],
do (
[n, q]: divide(n, b),
v: cons(q, v),
if n=0 then return(v)))$
binary(n) := simplode(digits(n, 2))$
binary(9000);
/*
10001100101000
*/</syntaxhighlight>
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">
-- MAXScript: Output decimal numbers from 0 to 16 as Binary : N.H. 2019
for k = 0 to 16 do
Line 2,426 ⟶ 3,664:
print binString
)
</syntaxhighlight>
</lang>
{{out}}
Output to MAXScript Listener:
Line 2,448 ⟶ 3,686:
"10000"
</pre>
 
=={{header|Maxima}}==
<lang maxima>digits([arg]) := block(
[n: first(arg), b: if length(arg) > 1 then second(arg) else 10, v: [ ], q],
do (
[n, q]: divide(n, b),
v: cons(q, v),
if n=0 then return(v)))$
binary(n) := simplode(digits(n, 2))$
binary(9000);
/*
10001100101000
*/</lang>
 
=={{header|Mercury}}==
<langsyntaxhighlight lang="mercury">:- module binary_digits.
:- interface.
 
Line 2,480 ⟶ 3,703:
print_binary_digits(N, !IO) :-
io.write_string(int_to_base_string(N, 2), !IO),
io.nl(!IO).</langsyntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.1937.30}}
<syntaxhighlight lang="min">(
<lang min>(2 over over mod 'div dip) :divmod2
symbol bin
(int :i ==> str :s)
(i (dup 2 <) 'string ('odd? ("1") ("0") if swap 1 shr) 'prefix linrec @s)
) ::
 
(0 1 2 5 50 9000) 'bin map ", " join puts!</syntaxhighlight>
(
:n () =list
(n 0 >) (n divmod2 list append #list @n) while
list reverse 'string map "" join
"^0+" "" replace ;remove leading zeroes
) :bin
 
(5 50 9000) (bin puts) foreach</lang>
{{out}}
<pre>0, 1, 10, 101, 110010, 10001100101000</pre>
<pre>
101
110010
10001100101000
</pre>
 
=={{header|MiniScript}}==
=== Iterative ===
<langsyntaxhighlight MiniScriptlang="miniscript">binary = function(n)
result = ""
while n
result = result + str(n%2) + result
n = floor(n/2)
end while
Line 2,516 ⟶ 3,732:
print binary(50)
print binary(9000)
print binary(0)</langsyntaxhighlight>
 
=== Recursive ===
<langsyntaxhighlight MiniScriptlang="miniscript">binary = function(n,result="")
if n == 0 then
if result == "" then return "0" else return result
Line 2,530 ⟶ 3,746:
print binary(50)
print binary(9000)
print binary(0)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,538 ⟶ 3,754:
0
</pre>
 
=={{header|mLite}}==
<langsyntaxhighlight lang="sml">fun binary
(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 = binary (n, [])
;
</syntaxhighlight>
</lang>
 
==== from the REPL ====
Line 2,555 ⟶ 3,770:
> binary 9000;
"10001100101000"</pre>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE Binary;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT Write,WriteLn,ReadChar;
Line 2,585 ⟶ 3,799:
 
ReadChar
END Binary.</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">MODULE Binary EXPORTS Main;
 
IMPORT IO, Fmt;
Line 2,598 ⟶ 3,811:
num := 150;
IO.Put(Fmt.Int(num, 2) & "\n");
END Binary.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,604 ⟶ 3,817:
10010110
</pre>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,623 ⟶ 3,835:
w_ = list.word(n_)
say w_.right(20)':' getBinaryDigits(w_)
end n_</langsyntaxhighlight>
{{out}}
<pre>
Line 2,631 ⟶ 3,843:
9000: 10001100101000
</pre>
=={{header|NewLisp}}==
 
<syntaxhighlight lang="newlisp">
;;; Using the built-in "bits" function
;;; For integers up to 9,223,372,036,854,775,807
(map println (map bits '(0 5 50 9000)))
;;; n > 0, "unlimited" size
(define (big-bits n)
(let (res "")
(while (> n 0)
(push (if (even? n) "0" "1") res)
(setq n (/ n 2)))
res))
;;; Example
(println (big-bits 1234567890123456789012345678901234567890L))
</syntaxhighlight>
<pre>
Output:
0
101
110010
10001100101000
1110100000110010010010000001110101110000001101101111110011101110001010110010111100010111111001011011001110001111110000101011010010
</pre>
=={{header|Nickle}}==
Using the Nickle output radix operator:
Line 2,644 ⟶ 3,879:
> 9000 # 2
10001100101000</pre>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc binDigits(x: BiggestInt, r: int): int =
## Calculates how many digits `x` has when each digit covers `r` bits.
result = 1
Line 2,669 ⟶ 3,903:
 
for i in 0..15:
echo toBin(i)</langsyntaxhighlight>
{{out}}
<pre>0
Line 2,688 ⟶ 3,922:
1111</pre>
 
===Version using strformat===
<syntaxhighlight lang="nim">import strformat
 
for n in 0..15:
echo fmt"{n:b}"</syntaxhighlight>
 
{{out}}
<pre>0
1
10
11
100
101
110
111
1000
1001
1010
1011
1100
1101
1110
1111</pre>
=={{header|Oberon-2}}==
<langsyntaxhighlight lang="oberon2">
MODULE BinaryDigits;
IMPORT Out;
Line 2,707 ⟶ 3,964:
OutBin(42); Out.Ln;
END BinaryDigits.
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,717 ⟶ 3,974:
101010
</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">class Binary {
function : Main(args : String[]) ~ Nil {
5->ToBinaryString()->PrintLine();
Line 2,725 ⟶ 3,981:
9000->ToBinaryString()->PrintLine();
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,732 ⟶ 3,988:
10001100101000
</pre>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let bin_of_int d =
let last_digit n = [|"0"; "1"|].(n land 1) in
if d < 0 then invalid_arg "bin_of_int" else
let rec aux lst = function
if d = 0 then "0" else
let rec aux| acc0 d-> =lst
if| dn =-> 0aux then(last_digit accn else:: lst) (n lsr 1)
aux (string_of_int (d land 1) :: acc) (d lsr 1)
in
String.concat "" (aux [last_digit d] (d lsr 1))
 
(* test *)
let () =
let d() = read_int[0; ()1; 2; 5; 50; 9000; in-5]
|> List.map bin_of_int |> String.concat ", " |> print_endline</syntaxhighlight>
Printf.printf "%8s\n" (bin_of_int d)</lang>
The output of negative integers is interesting, as it shows the [[wp:Two's_complement|two's complement]] representation and the width of Int on the system.
{{out}}
<pre>
0, 1, 10, 101, 110010, 10001100101000, 1111111111111111111111111111011
</pre>
 
=={{header|Oforth}}==
Line 2,764 ⟶ 4,023:
ok
</pre>
=={{header|Ol}}==
 
<syntaxhighlight lang="scheme">
(print (number->string 5 2))
(print (number->string 50 2))
(print (number->string 9000 2))
</syntaxhighlight>
{{Out}}
<pre>
101
110010
10001100101000
</pre>
=={{header|OxygenBasic}}==
The Assembly code uses block structures to minimise the use of labels.
<langsyntaxhighlight lang="oxygenbasic">
 
function BinaryBits(sys n) as string
Line 2,811 ⟶ 4,081:
 
print BinaryBits 0xaa 'result 10101010
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
<lang parigp>bin(n:int)=concat(apply(s->Str(s),binary(n)))</lang>
 
=={{header|Panda}}==
<syntaxhighlight lang ="panda">0..15.radix:2 nl</langsyntaxhighlight>
{{out}}
<pre>0
Line 2,835 ⟶ 4,101:
1110
1111</pre>
=={{header|PARI/GP}}==
<syntaxhighlight lang="parigp">bin(n:int)=concat(apply(s->Str(s),binary(n)))</syntaxhighlight>
=={{header|Pascal}}==
{{works with|Free Pascal}}
FPC compiler Version 2.6 upwards.The obvious version.
<langsyntaxhighlight lang="pascal">program IntToBinTest;
{$MODE objFPC}
uses
Line 2,866 ⟶ 4,134:
IntBinTest(5);IntBinTest(50);IntBinTest(5000);
IntBinTest(0);IntBinTest(NativeUint(-1));
end.</langsyntaxhighlight>
{{out}}
<pre> 5 101
Line 2,878 ⟶ 4,146:
Beware of the endianess of the constant.
I check performance with random Data.
<langsyntaxhighlight lang="pascal">
program IntToPcharTest;
uses
Line 2,984 ⟶ 4,252:
Writeln(cnt/rounds+1:6:3);
FreeMem(s);
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,998 ⟶ 4,266:
Time 0.175 secs, average stringlength 62.000
..the obvious version takes about 1.1 secs generating the string takes most of the time..</pre>
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="pascal">
begin
foreach var number in |5, 50, 9000| do
Writeln($'{number,4} - {Convert.ToString(number,2)}');
end.
</syntaxhighlight>
{{out}}
<pre>
5 - 101
50 - 110010
9000 - 10001100101000
</pre>
 
=={{header|Peloton}}==
<langsyntaxhighlight lang="sgml"><@ defbaslit>2</@>
 
<@ saybaslit>0</@>
Line 3,006 ⟶ 4,287:
<@ saybaslit>50</@>
<@ saybaslit>9000</@>
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">for (5, 50, 9000) {
printf "%b\n", $_;
}</langsyntaxhighlight>
<pre>
101
Line 3,017 ⟶ 4,298:
10001100101000
</pre>
 
=={{header|Perl 6}}==
{{works with|Rakudo|2015.12}}
<lang perl6>say .fmt("%b") for 5, 50, 9000;</lang>
<pre>
101
110010
10001100101000
</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>printf(1,"%b\n",5)
<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>
printf(1,"%b\n",50)
<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>
printf(1,"%b\n",9000)</lang>
<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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 3,037 ⟶ 4,310:
10001100101000
</pre>
=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">def printBinary
"The decimal value " print dup print " should produce an output of " print
20 int>bit
len 1 -1 3 tolist
for
get not
if
-1 del
else
exitfor
endif
endfor
len 1 -1 3 tolist
for
get print
endfor
nl
enddef
 
5 printBinary
50 printBinary
9000 printBinary</syntaxhighlight>
 
Other solution
<syntaxhighlight lang="phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/Binary_digits
by Galileo, 05/2022 #/
 
include ..\Utilitys.pmt
 
def printBinary
0 >ps >ps
( "The decimal value " tps " should produce an output of " ) lprint
ps> 20 int>bit
( len 1 -1 ) for
get dup ps> or if print 1 >ps else drop 0 >ps endif
endfor
nl
enddef
5 printBinary
50 printBinary
9000 printBinary
</syntaxhighlight>
{{out}}
<pre>The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
 
=== Press any key to exit ===</pre>
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
echo decbin(5);
echo decbin(50);
echo decbin(9000);</langsyntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|Picat}}==
<syntaxhighlight lang="picat"> foreach(I in [5,50,900])
println(to_binary_string(I))
end.</syntaxhighlight>
 
{{out}}
<pre>101
110010
1110000100</pre>
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">: (bin 5)
-> "101"
 
Line 3,056 ⟶ 4,387:
 
: (bin 9000)
-> "10001100101000"</langsyntaxhighlight>
 
=={{header|Piet}}==
 
Line 3,215 ⟶ 4,545:
 
Explanation of program flow and image download link on my user page: [http://rosettacode.org/wiki/User:Albedo#Binary_Digits]
 
=={{header|PL/I}}==
Displays binary output trivially, but with leading zeros:
<langsyntaxhighlight lang="pli">put edit (25) (B);</langsyntaxhighlight>
{{out}}
<pre>Output: 0011001
</pre>
With leading zero suppression:
<langsyntaxhighlight lang="pli"> declare text character (50) initial (' ');
 
put string(text) edit (25) (b);
Line 3,229 ⟶ 4,558:
 
put string(text) edit (2147483647) (b);
put skip list (trim(text, '0'));</langsyntaxhighlight>
{{out}}
<pre>
Line 3,235 ⟶ 4,564:
1111111111111111111111111111111
</pre>
=={{header|PL/M}}==
<syntaxhighlight lang="plm">100H:
 
/* CP/M BDOS CALL */
BDOS: PROCEDURE (FN, ARG);
DECLARE FN BYTE, ARG ADDRESS;
GO TO 5;
END BDOS;
 
/* PRINT STRING */
PRINT: PROCEDURE (STRING);
DECLARE STRING ADDRESS;
CALL BDOS(9, STRING);
END PRINT;
 
/* PRINT BINARY NUMBER */
PRINT$BINARY: PROCEDURE (N);
DECLARE S (19) BYTE INITIAL ('................',13,10,'$');
DECLARE (N, P) ADDRESS, C BASED P BYTE;
P = .S(16);
BIT:
P = P - 1;
C = (N AND 1) + '0';
IF (N := SHR(N,1)) <> 0 THEN GO TO BIT;
CALL PRINT(P);
END PRINT$BINARY;
 
/* EXAMPLES FROM TASK */
DECLARE TEST (3) ADDRESS INITIAL (5, 50, 9000);
DECLARE I BYTE;
 
DO I = 0 TO LAST(TEST);
CALL PRINT$BINARY(TEST(I));
END;
 
CALL BDOS(0,0);
EOF</syntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
=={{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.
<langsyntaxhighlight lang="powerbasic">
#COMPILE EXE
#DIM ALL
Line 3,251 ⟶ 4,619:
PRINT STR$(d(i)) & ": " & BIN$(d(i)) & " (" & BIN$(d(i), 32) & ")"
NEXT i
END FUNCTION</langsyntaxhighlight>
{{out}}<pre>
5: 101 (00000000000000000000000000000101)
Line 3,257 ⟶ 4,625:
9000: 10001100101000 (00000000000000000010001100101000)
</pre>
 
 
=={{header|PowerShell}}==
{{libheader|Microsoft .NET Framework}}
<langsyntaxhighlight PowerShelllang="powershell">@(5,50,900) | foreach-object { [Convert]::ToString($_,2) }</langsyntaxhighlight>
{{out}}
<pre>101
110010
1110000100</pre>
 
=={{header|Processing}}==
<langsyntaxhighlight lang="processing">println(Integer.toBinaryString(5)); // 101
println(Integer.toBinaryString(50)); // 110010
println(Integer.toBinaryString(9000)); // 10001100101000</langsyntaxhighlight>
Processing also has a binary() function, but this returns zero-padded results
<langsyntaxhighlight lang="processing">println(binary(5)); // 00000000000101
println(binary(50)); // 00000000110010
println(binary(9000)); // 10001100101000</langsyntaxhighlight>
 
=={{header|Prolog}}==
{{works with|SWI Prolog}}
{{works with|GNU Prolog}}
<langsyntaxhighlight lang="prolog">
binary(X) :- format('~2r~n', [X]).
main :- maplist(binary, [5,50,9000]), halt.
</syntaxhighlight>
</lang>
{{out}}
<pre>101
110010
10001100101000</pre>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole()
PrintN(Bin(5)) ;101
PrintN(Bin(50)) ;110010
Line 3,296 ⟶ 4,659:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
 
=={{header|Python}}==
===String.format() method===
{{works with|Python|3.X and 2.6+}}
<langsyntaxhighlight lang="python">>>> for i in range(16): print('{0:b}'.format(i))
 
0
Line 3,322 ⟶ 4,684:
1101
1110
1111</langsyntaxhighlight>
 
===Built-in bin() function===
{{works with|Python|3.X and 2.6+}}
<langsyntaxhighlight lang="python">>>> for i in range(16): print(bin(i)[2:])
 
0
Line 3,343 ⟶ 4,705:
1101
1110
1111</langsyntaxhighlight>
Pre-Python 2.6:
<langsyntaxhighlight 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'
>>> for i in range(16): print(bin(i))
Line 3,364 ⟶ 4,726:
1101
1110
1111</langsyntaxhighlight>
 
===Custom functions===
 
Defined in terms of a more general '''showIntAtBase''' function:
<langsyntaxhighlight lang="python">'''Binary strings for integers'''
 
 
Line 3,458 ⟶ 4,820:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Mapping showBinary over integer list:
Line 3,472 ⟶ 4,834:
 
Or, using a more specialised function to decompose an integer to a list of boolean values:
<langsyntaxhighlight lang="python">'''Decomposition of an integer to a string of booleans.'''
 
 
Line 3,592 ⟶ 4,954:
# MAIN -------------------------------------------------
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Mapping a composed function:
Line 3,603 ⟶ 4,965:
50 -> 110010
9000 -> 10001100101000</pre>
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
Print DecToBin$(5)
Print DecToBin$(50)
Print DecToBin$(9000)
 
Print BinToDec$(DecToBin$(5)) ' 101
Print BinToDec$(DecToBin$(50)) '110010
Print BinToDec$(DecToBin$(9000)) ' 10001100101000
 
End
 
Function DecToBin$ (digit As Integer)
DecToBin$ = "Error"
If digit < 1 Then
Print " Error number invalid for conversion to binary"
DecToBin$ = "error of input"
Exit Function
Else
 
Dim As Integer TempD
Dim binaryD As String
binaryD = ""
TempD = digit
Do
binaryD = Right$(Str$(TempD Mod 2), 1) + binaryD
TempD = TempD \ 2
Loop Until TempD = 0
DecToBin$ = binaryD
End If
End Function
 
Function BinToDec$ (digitB As String)
BinToDec$ = "Error"
If Len(digitB) < 1 Then
Print " Error number invalid for conversion to decimal"
BinToDec$ = "error of input"
Exit Function
Else
Dim As Integer TempD
Dim binaryD As String
binaryD = digitB
TempD = 0
Do
TempD = TempD + ((2 ^ (Len(binaryD) - 1)) * Val(Left$(binaryD, 1)))
binaryD = Right$(binaryD, Len(binaryD) - 1)
Loop Until Len(binaryD) = 0
BinToDec$ = LTrim$(Str$(TempD))
End If
End Function
 
 
</syntaxhighlight>
=={{header|Quackery}}==
Quackery provides built-in radix control, much like Forth.
<syntaxhighlight lang="quackery">
2 base put ( Numbers will be output in base 2 now. )
( Bases from 2 to 36 (inclusive) are supported. )
 
5 echo cr
50 echo cr
9000 echo cr
 
base release ( It's best to clean up after ourselves. )
( Numbers will be output in base 10 now. )
</syntaxhighlight>
 
A user-defined conversion might look something like this:
<syntaxhighlight lang="quackery">
[ [] swap
[ 2 /mod digit
swap dip join
dup not until ]
drop reverse ] is bin ( n --> $ )
 
5 bin echo$ cr
50 bin echo$ cr
9000 bin echo$ cr
</syntaxhighlight>
{{out}}
<pre>
101
110010
10001100101000
</pre>
=={{header|R}}==
<langsyntaxhighlight lang="rsplus">
dec2bin <- function(num) {
ifelse(num == 0,
Line 3,615 ⟶ 5,063:
cat(dec2bin(anumber),"\n")
}
</syntaxhighlight>
</lang>
'''output'''
<pre>
Line 3,623 ⟶ 5,071:
10001100101000
</pre>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
;; Option 1: binary formatter
Line 3,631 ⟶ 5,078:
;; Option 2: explicit conversion
(for ([i 16]) (displayln (number->string i 2)))
</syntaxhighlight>
</lang>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" line>say .fmt("%b") for 5, 50, 9000;</syntaxhighlight>
<pre>
101
110010
10001100101000
</pre>
 
Alternatively:
 
<syntaxhighlight lang="raku" line>say .base(2) for 5, 50, 9000;</syntaxhighlight>
<pre>101
110010
10001100101000</pre>
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
<lang vb>
'Convert Integer to binary string
Print "bin 5 = ", bin$(5)
Line 3,639 ⟶ 5,102:
Print "bin 9000 = ",bin$(9000)
sleep 10
</syntaxhighlight>
</lang>
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">Red []
 
foreach number [5 50 9000] [
Line 3,648 ⟶ 5,111:
print reduce [ pad/left number 5 binstr ]
]
</syntaxhighlight>
</lang>
'''output'''
<pre> 5 101
Line 3,654 ⟶ 5,117:
9000 10001100101000
</pre>
 
=={{header|Retro}}==
<langsyntaxhighlight Retrolang="retro">9000 50 5 3 [ binary putn cr decimal ] times</langsyntaxhighlight>
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <Prout <Binary 5>
<Binary 50>
<Binary 9000>>;
};
 
Binary {
0 = '0\n';
s.N = <Binary1 s.N> '\n';
};
 
Binary1 {
0 = ;
s.N, <Divmod s.N 2>: (s.R) s.D = <Binary1 s.R> <Symb s.D>;
};</syntaxhighlight>
{{out}
<pre>101
110010
10001100101000</pre>
 
=={{header|REXX}}==
Line 3,663 ⟶ 5,145:
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).
<langsyntaxhighlight REXXlang="rexx">/*REXX program to convert several decimal numbers to binary (or base 2). */
numeric digits 1000 /*ensure we can handle larger numbers. */
@.=; @.1= 0
Line 3,673 ⟶ 5,155:
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. */
end /*j*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output}}
<pre>
Line 3,685 ⟶ 5,167:
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.
<langsyntaxhighlight REXXlang="rexx">/*REXX program to convert several decimal numbers to binary (or base 2). */
@.=; @.1= 0
@.2= 5
Line 3,695 ⟶ 5,177:
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. */
end /*j*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
 
===concise version===
This version handles the case of zero a bit more obtusely, but concisely.
<langsyntaxhighlight REXXlang="rexx">/*REXX program to convert several decimal numbers to binary (or base 2). */
@.=; @.1= 0
@.2= 5
Line 3,709 ⟶ 5,191:
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. */
end /*j*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
 
===conforming version===
This REXX version conforms to the strict output requirements of this task (just show the binary output without any blanks).
<langsyntaxhighlight REXXlang="rexx">/*REXX program to convert several decimal numbers to binary (or base 2). */
numeric digits 200 /*ensure we can handle larger numbers. */
@.=; @.1= 0
Line 3,727 ⟶ 5,209:
if y=='' then y=0 /*handle the special case of 0 (zero).*/
say y /*display binary number to the terminal*/
end /*j*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output}}
<pre>
Line 3,739 ⟶ 5,221:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see "Number to convert : "
give a
Line 3,752 ⟶ 5,234:
else see 0 ok
next
</syntaxhighlight>
</lang>
 
=={{header|Roc}}==
<syntaxhighlight lang="roc">binstr : Int * -> Str
binstr = \n ->
if n < 2 then
Num.toStr n
else
Str.concat (binstr (Num.shiftRightZfBy n 1)) (Num.toStr (Num.bitwiseAnd n 1))</syntaxhighlight>
 
=={{header|RPL}}==
RPL handles both floating point numbers and binary integers, but the latter are visualized with a <code>#</code> at the beginning and a specific letter at the end identifying the number base, according to the current display mode setting. 42 will then be displayed # 42d, # 2Ah, # 52o or # 101010b depending on the display mode set by resp. <code>DEC</code>, <code>HEX</code>, <code>OCT</code> or <code>BIN</code>.
 
To comply with the task, we have just to remove these characters.
{{works with|Halcyon Calc|4.2.7}}
≪ BIN R→B →STR 3 OVER SIZE 1 - SUB ≫
'→PLNB' STO
{{in}}
<pre>
5 →PLNB
50 →PLNB
9000 →PLNB
</pre>
{{out}}
<pre>
3: "101"
2: "110010"
1: "10001100101000"
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">[5,50,9000].each do |n|
puts "%b" % n
end</langsyntaxhighlight>
or
<langsyntaxhighlight lang="ruby">for n in [5,50,9000]
puts n.to_s(2)
end</langsyntaxhighlight>
{{out}}
<pre>101
Line 3,768 ⟶ 5,278:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">input "Number to convert:";a
while 2^(n+1) < a
n = n + 1
Line 3,781 ⟶ 5,291:
print 0;
end if
next</langsyntaxhighlight>
{{out}}
<pre>Number to convert:?9000
10001100101000</pre>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn main() {
for i in 0..8 {
println!("{:b}", i)
}
}</langsyntaxhighlight>
Outputs:
<pre>0
Line 3,801 ⟶ 5,310:
110
111</pre>
 
 
=={{header|S-lang}}==
<langsyntaxhighlight Slang="s-lang">define int_to_bin(d)
{
variable m = 0x40000000, prn = 0, bs = "";
Line 3,824 ⟶ 5,331:
() = printf("%s\n", int_to_bin(5));
() = printf("%s\n", int_to_bin(50));
() = printf("%s\n", int_to_bin(9000));</langsyntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
 
=={{header|S-BASIC}}==
<syntaxhighlight lang = "BASIC">
 
rem - Return binary representation of n
 
function bin$(n = integer) = string
var s = string
s = ""
while n > 0 do
begin
if (n - (n / 2) * 2) = 0 then
s = "0" + s
else
s = "1" + s
n = n / 2
end
end = s
 
rem - exercise the function
 
print "5 = "; bin$(5)
print "50 = "; bin$(50)
print "9000 = "; bin$(9000)
 
end
</syntaxhighlight>
{{out}}
<pre>
5 = 101
50 = 110010
9000 = 10001100101000
</pre>
 
=={{header|Scala}}==
Scala has an implicit conversion from <code>Int</code> to <code>RichInt</code> which has a method <code>toBinaryString</code>.
<langsyntaxhighlight lang="scala">scala> (5 toBinaryString)
res0: String = 101
 
Line 3,839 ⟶ 5,379:
 
scala> (9000 toBinaryString)
res2: String = 10001100101000</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(display (number->string 5 2)) (newline)
(display (number->string 50 2)) (newline)
(display (number->string 9000 2)) (newline)</langsyntaxhighlight>
 
=={{header|sed}}==
<syntaxhighlight lang="sed">: a
s/^0*/d/
/^d[1-9]/t b
b e
: b
s/d[01]/0&/
s/d[23]/1&/
s/d[45]/2&/
s/d[67]/3&/
s/d[89]/4&/
t d
b a
: c
s/D[01]/5&/
s/D[23]/6&/
s/D[45]/7&/
s/D[67]/8&/
s/D[89]/9&/
t d
b a
: d
s/[dD][02468]/d/
t b
s/[dD][13579]/D/
t c
: e
s/^dD/D/
y/dD/01/</syntaxhighlight>
{{out}}
<pre>
$ echo $(seq 0 16 | sed -f binary-digits.sed)
0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 10000
$ printf '%s\n' 50 9000 1996677482718355282095361651 | sed -f binary-digits.sed
110010
10001100101000
1100111001110011100111001110011100111001110011100111001110011100111001110011100111001110011
</pre>
 
=={{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.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 3,858 ⟶ 5,436:
writeln(number radix 2);
end for;
end func;</langsyntaxhighlight>
{{out}}
<pre>
Line 3,878 ⟶ 5,456:
1111
10000
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program binary_digits;
loop for n in [5, 50, 9000] do
print(bin n);
end loop;
 
op bin(n);
return reverse +/[str [n mod 2, n div:=2](1) : until n=0];
end op;
end program;</syntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
 
=={{header|SequenceL}}==
<syntaxhighlight lang="sequencel">main := toBinaryString([5, 50, 9000]);
 
toBinaryString(number(0)) :=
let
val := "1" when number mod 2 = 1 else "0";
in
toBinaryString(floor(number/2)) ++ val when floor(number/2) > 0
else
val;</syntaxhighlight>
 
{{out}}
<pre>
["101","110010","10001100101000"]
</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">[5, 50, 9000].each { |n|
say n.as_bin;
}</langsyntaxhighlight>
{{out}}
<pre>101
Line 3,889 ⟶ 5,498:
10001100101000</pre>
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">BEGIN
 
PROCEDURE OUTINTBIN(N); INTEGER N;
Line 3,903 ⟶ 5,512:
END;
 
END</langsyntaxhighlight>
{{out}}
<pre>
Line 3,910 ⟶ 5,519:
10001100101000
</pre>
 
=={{header|SequenceL}}==
<lang sequencel>main := toBinaryString([5, 50, 9000]);
 
toBinaryString(number(0)) :=
let
val := "1" when number mod 2 = 1 else "0";
in
toBinaryString(floor(number/2)) ++ val when floor(number/2) > 0
else
val;</lang>
 
{{out}}
<pre>
["101","110010","10001100101000"]
</pre>
 
 
=={{header|SkookumScript}}==
 
<langsyntaxhighlight lang="javascript">println(5.binary)
println(50.binary)
println(9000.binary)</langsyntaxhighlight>
Or looping over a list of numbers:
<langsyntaxhighlight lang="javascript">{5 50 9000}.do[println(item.binary)]</langsyntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">5 printOn: Stdout radix:2
50 printOn: Stdout radix:2
9000 printOn: Stdout radix:2</langsyntaxhighlight>
or:
<langsyntaxhighlight lang="smalltalk">#(5 50 9000) do:[:each | each printOn: Stdout radix:2. Stdout cr]</langsyntaxhighlight>
=={{header|SNOBOL4}}==
<syntaxhighlight lang="snobol4">
define('bin(n,r)') :(bin_end)
bin bin = le(n,0) r :s(return)
bin = bin(n / 2, REMDR(n,2) r) :(return)
bin_end
 
output = bin(5)
output = bin(50)
output = bin(9000)
end</syntaxhighlight>
{{out}}
<pre>
101
110010
10001100101000
</pre>
=={{header|SNUSP}}==
<syntaxhighlight lang="snusp">
<lang SNUSP>
/recurse\
$,binary!\@\>?!\@/<@\.#
Line 3,954 ⟶ 5,560:
/<+>- \ div2
\?!#-?/+# mod2
</syntaxhighlight>
</lang>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">print (Int.fmt StringCvt.BIN 5 ^ "\n");
print (Int.fmt StringCvt.BIN 50 ^ "\n");
print (Int.fmt StringCvt.BIN 9000 ^ "\n");</langsyntaxhighlight>
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">for num in [5, 50, 9000] {
println(String(num, radix: 2))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,969 ⟶ 5,574:
110010
10001100101000</pre>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc num2bin num {
# Convert to _fixed width_ big-endian 32-bit binary
binary scan [binary format "I" $num] "B*" binval
# Strip useless leading zeros by reinterpreting as a big decimal integer
scan $binval "%lld"
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">for {set x 0} {$x < 16} {incr x} {
puts [num2bin $x]
}
Line 3,984 ⟶ 5,588:
puts [num2bin 5]
puts [num2bin 50]
puts [num2bin 9000]</langsyntaxhighlight>
{{out}}
<pre>
Line 4,008 ⟶ 5,612:
10001100101000
</pre>
<br>
 
Or you can use the builtin format:
<syntaxhighlight lang="tcl">foreach n {0 1 5 50 9000} {
puts [format "%4u: %b" $n $n]
}</syntaxhighlight>
{{out}}
<pre> 0: 0
1: 1
5: 101
50: 110010
9000: 10001100101000</pre>
=={{header|TI-83 BASIC}}==
Using Standard TI-83 BASIC
<langsyntaxhighlight lang="ti83b">PROGRAM:BINARY
:Disp "NUMBER TO"
:Disp "CONVERT:"
Line 4,029 ⟶ 5,643:
:N-1→N
:End
:Disp B</langsyntaxhighlight>
Alternate using a string to display larger numbers.
<langsyntaxhighlight lang="ti83b">PROGRAM:BINARY
:Input X
:" "→Str1
Line 4,039 ⟶ 5,653:
:iPart(X)→X
:End
:Str1</langsyntaxhighlight>
Using the baseInput() "real(25," function from [http://www.detachedsolutions.com/omnicalc/ Omnicalc]
<langsyntaxhighlight lang="ti83b">PROGRAM:BINARY
:Disp "NUMBER TO"
:Disp "CONVERT"
:Input "Str1"
:Disp real(25,Str1,10,2)</langsyntaxhighlight>
 
More compact version:
<langsyntaxhighlight lang="ti83b">:Input "DEC: ",D
:" →Str1
:If not(D:"0→Str1
Line 4,060 ⟶ 5,674:
:End
:Disp Str1
</syntaxhighlight>
</lang>
 
=={{header|uBasic/4tH}}==
This will convert any decimal number to any base between 2 and 16.
<syntaxhighlight lang="text">Do
Input "Enter base (1<X<17): "; b
While (b < 2) + (b > 16)
Line 4,096 ⟶ 5,709:
130 Print "D"; : Return
140 Print "E"; : Return
150 Print "F"; : Return</langsyntaxhighlight>
{{out}}
<pre>Enter base (1<X<17): 2
Line 4,103 ⟶ 5,716:
 
0 OK, 0:775</pre>
 
=={{header|UNIX Shell}}==
Since POSIX does not specify local variables, make use of <code>set</code> for highest portability.
<lang sh># Define a function to output binary digits
<syntaxhighlight lang="sh">bin() {
tobinary() {
set -- "${1:-0}" ""
# We use the bench calculator for our conversion
echo while [ 1 -lt "obase=2;$1"|bc ]
do
set -- $(($1 >> 1)) $(($1 & 1))$2
done
echo "$1$2"
}
 
echo $(for i in 0 1 2 5 50 9000; do bin $i; done)</syntaxhighlight>
# Call the function with each of our values
{{out}}
tobinary 5
<pre>0 1 10 101 110010 10001100101000</pre>
tobinary 50</lang>
 
=={{header|VBA}}==
Line 4,134 ⟶ 5,752:
Places is useful for padding the return value with leading 0s (zeros).
 
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 4,173 ⟶ 5,791:
End If
End Function
</syntaxhighlight>
</lang>
{{out}}
<pre>The decimal value 5 should produce an output of : 101
Line 4,181 ⟶ 5,799:
The decimal value 9000 should produce an output of : 10001100101000
The decimal value 9000 should produce an output of : Error : Number is too large ! (Number must be < 511)</pre>
 
 
=={{header|Vedit macro language}}==
This implementation reads the numeric values from user input and writes the converted binary values in the edit buffer.
<langsyntaxhighlight lang="vedit">repeat (ALL) {
#10 = Get_Num("Give a numeric value, -1 to end: ", STATLINE)
if (#10 < 0) { break }
Line 4,201 ⟶ 5,817:
EOL
Ins_Newline
Return </langsyntaxhighlight>
Example output when values 0, 1, 5, 50 and 9000 were entered:
<pre>
Line 4,210 ⟶ 5,826:
10001100101000
</pre>
 
=={{header|Vim Script}}==
<langsyntaxhighlight lang="vim">function Num2Bin(n)
let n = a:n
let s = ""
Line 4,232 ⟶ 5,847:
echo Num2Bin(5)
echo Num2Bin(50)
echo Num2Bin(9000)</langsyntaxhighlight>
 
{{Out}}
Line 4,238 ⟶ 5,853:
110010
10001100101000</pre>
 
=={{header|Visual Basic}}==
{{works with|Visual Basic|VB6 Standard}}
<syntaxhighlight lang="vb">
<lang vb>
Public Function Bin(ByVal l As Long) As String
Dim i As Long
Line 4,276 ⟶ 5,890:
Debug.Print Bin(9000)
End Sub
</syntaxhighlight>
</lang>
{{out}}
<pre>101
110010
10001100101000</pre>
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">Module Program
Sub Main
For Each number In {5, 50, 9000}
Line 4,289 ⟶ 5,902:
Next
End Sub
End Module</langsyntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
 
=={{header|Visual FoxPro}}==
<langsyntaxhighlight lang="vfp">
*!* Binary Digits
CLEAR
Line 4,322 ⟶ 5,934:
RETURN FLOOR(v)
ENDFUNC
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,329 ⟶ 5,941:
10001100101000
</pre>
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">fn main() {
for i in 0..16 {
println("${i:b}")
}
}</syntaxhighlight>
{{out}}
<pre>
0
1
10
11
100
101
110
111
1000
1001
1010
1011
1100
1101
1110
1111
</pre>
 
=={{header|VTL-2}}==
<syntaxhighlight lang="vtl2">10 N=5
20 #=100
30 N=50
40 #=100
50 N=9000
100 ;=!
110 I=18
120 I=I-1
130 N=N/2
140 :I)=%
150 #=0<N*120
160 ?=:I)
170 I=I+1
180 #=I<18*160
190 ?=""
200 #=;</syntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|VBScript}}==
Using no Math....
<syntaxhighlight lang="vb">
Option Explicit
Dim bin
bin=Array(" "," I"," I "," II"," I "," I I"," II "," III","I ","I I","I I ","I II"," I ","II I","III ","IIII")
 
Function num2bin(n)
Dim s,i,n1,n2
s=Hex(n)
For i=1 To Len(s)
n1=Asc(Mid(s,i,1))
If n1>64 Then n2=n1-55 Else n2=n1-48
num2bin=num2bin & bin(n2)
Next
num2bin=Replace(Replace(LTrim(num2bin)," ","0"),"I",1)
End Function
Sub print(s):
On Error Resume Next
WScript.stdout.WriteLine (s)
If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub
print num2bin(5)
print num2bin(50)
print num2bin(9000)
</syntaxhighlight>
{{out}}
<small>
<pre>
101
110010
10001100101000
</pre>
</small>
 
=={{header|Whitespace}}==
Line 4,334 ⟶ 6,028:
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]].
 
<syntaxhighlight lang="whitespace">
<lang Whitespace>
 
Line 4,373 ⟶ 6,067:
 
 
</langsyntaxhighlight>
 
It was generated from the following pseudo-Assembly.
 
<langsyntaxhighlight lang="asm">push 0
; Increment indefinitely.
0:
Line 4,409 ⟶ 6,103:
3:
pop
ret</langsyntaxhighlight>
 
=={{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:
<langsyntaxhighlight lang="wortel">\.toString 2
; the following function also casts the string to a number
^(@+ \.toString 2)</langsyntaxhighlight>
To output to the console:
<langsyntaxhighlight lang="wortel">@each ^(console.log \.toString 2) [5 50 900]</langsyntaxhighlight>
Outputs: <pre>
101
110010
1110000100</pre>
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
System.print("Converting to binary:")
for (i in [5, 50, 9000]) Fmt.print("$d -> $b", i, i)</syntaxhighlight>
 
{{out}}
<pre>
Converting to binary:
5 -> 101
50 -> 110010
9000 -> 10001100101000
</pre>
 
=={{header|X86 Assembly}}==
Translation of XPL0. Assemble with tasm, tlink /t
<langsyntaxhighlight lang="asm"> .model tiny
.code
.486
Line 4,453 ⟶ 6,161:
int 29h ;display character
ret
end start</langsyntaxhighlight>
 
{{out}}
Line 4,461 ⟶ 6,169:
10001100101000
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic code declarations
 
proc BinOut(N); \Output N in binary
Line 4,479 ⟶ 6,186:
I:= I+1;
until KeyHit or I=0;
]</langsyntaxhighlight>
 
{{out}}
Line 4,498 ⟶ 6,205:
100000010100001
</pre>
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">dim a(3)
a(0) = 5
a(1) = 50
a(2) = 9000
for i = 0 to 2
print a(i) using "####", " -> ", bin$(a(i))
next i
end</syntaxhighlight>
=={{header|Z80 Assembly}}==
{{trans|8086 Assembly}}
 
<syntaxhighlight lang="z80">org &8000
=={{header|zkl}}==
PrintChar equ &BB5A ;syscall - prints accumulator to Amstrad CPC's screen
<lang zkl>(9000).toString(2)</lang>
<lang zkl>T(5,50,9000).apply("toString",2) //--> L("101","110010","10001100101000")</lang>
<lang zkl>"%.2B".fmt(9000)</lang>
 
 
main:
 
ld hl,TestData0
call PrintBinary_NoLeadingZeroes
 
ld hl,TestData1
call PrintBinary_NoLeadingZeroes
 
ld hl,TestData2
call PrintBinary_NoLeadingZeroes
 
ret
 
TestData0:
byte 5,255
TestData1:
byte 5,0,255
TestData2:
byte 9,0,0,0,255
 
temp:
byte 0
;temp storage for the accumulator
; we can't use the stack to preserve A since that would also preserve the flags.
 
 
PrintBinary_NoLeadingZeroes:
;setup:
ld bc,&8000 ;B is the revolving bit mask, C is the "have we seen a zero yet" flag
 
 
NextDigit:
ld a,(hl)
inc hl
cp 255
jp z,Terminated
ld (temp),a
NextBit:
ld a,(temp)
and b
jr z,PrintZero
; else, print one
ld a,'1' ;&31
call &BB5A
set 0,b ;bit 0 of B is now 1, so we can print zeroes now.
jr Predicate
PrintZero:
ld a,b
or a
jr z,Predicate ;if we haven't seen a zero yet, don't print a zero.
ld a,'0' ;&30
call &BB5A
Predicate:
rrc b
;rotate the mask right by one. If it sets the carry,
; it's back at the start, and we need to load the next byte.
jr nc,NextBit
jr NextDigit ;back to top
Terminated:
ld a,13
call &BB5A
ld a,10
jp &BB5A ;its ret will return for us.</syntaxhighlight>
 
 
This is another version. Output of the result over port 0A hex.
<syntaxhighlight lang="z80">
; HL contains the value to be converted
ld hl,5
call binary
 
ld hl,50
call binary
 
ld hl,9000
call binary
 
halt
 
; Convert to binary
; The OUT(0x0A),A command does the output to an device
binary: push hl
push bc
ld c,0x00
call gobin
ld h,l
call gobin
pop bc
pop hl
ret
 
gobin: ld b,0x08
 
bitloop: ld a,h
bit 7,h
jr nz,one
zero: ld a,c
or a
jr z,end1
ld a,"0"
out (0x0a),a
jr end1
 
one: ld a,"1"
ld c,0x01
out (0x0a),a
 
end1: ld a,h
rlca
ld h,a
djnz bitloop
 
ret</syntaxhighlight>
=={{header|zkl}}==
<syntaxhighlight lang="zkl">(9000).toString(2)</syntaxhighlight>
<syntaxhighlight lang="zkl">T(5,50,9000).apply("toString",2) //--> L("101","110010","10001100101000")</syntaxhighlight>
<syntaxhighlight lang="zkl">"%.2B".fmt(9000)</syntaxhighlight>
=={{header|ZX Spectrum Basic}}==
<langsyntaxhighlight lang="zxbasic">10 LET n=5: GO SUB 1000: PRINT s$
20 LET n=50: GO SUB 1000: PRINT s$
30 LET n=9000: GO SUB 1000: PRINT s$
Line 4,518 ⟶ 6,359:
1070 IF (sf <> 0) THEN LET s$=s$+d$
1080 NEXT l
1090 RETURN</langsyntaxhighlight>
153

edits