Binary digits: Difference between revisions

Add Refal
m (syntax highlighting fixup automation)
(Add Refal)
(46 intermediate revisions by 19 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
<syntaxhighlight 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:</syntaxhighlight>
 
{{out}}
<pre>
 
Note that 0815 reads numeric input in hexadecimal.
 
<syntaxhighlight lang=bash>echo -e "5\n32\n2329" | 0815 bin.0
101
110010
</pre>
10001100101001</syntaxhighlight>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">L(n) [0, 5, 50, 9000]
print(‘#4 = #.’.format(n, bin(n)))</syntaxhighlight>
{{out}}
Line 49 ⟶ 34:
9000 = 10001100101000
</pre>
 
=={{header|360 Assembly}}==
<syntaxhighlight lang="360asm">* Binary digits 27/08/2015
BINARY CSECT
USING BINARY,R12
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>
<syntaxhighlight lang="6502asm">
; C64 - Binary digits
; http://rosettacode.org/wiki/Binary_digits
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
Line 270 ⟶ 274:
 
</pre>
 
=={{header|8086 Assembly}}==
<syntaxhighlight lang="asm"> .model small
.stack 1024
.data
Line 357 ⟶ 360:
ret
PrintBinary_NoLeadingZeroes endp</syntaxhighlight>
 
=={{header|8th}}==
<syntaxhighlight lang=forth>
2 base drop
#50 . cr
</syntaxhighlight>
{{out}}
<pre>
110010
</pre>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang=AArch64"aarch64 Assemblyassembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program binarydigit.s */
Line 532 ⟶ 524:
The decimal value +1 should produce an output of 1
</pre>
 
=={{header|ACL2}}==
<syntaxhighlight lang=Lisp"lisp">(include-book "arithmetic-3/top" :dir :system)
 
(defun bin-string-r (x)
Line 549 ⟶ 540:
"0"
(bin-string-r x)))</syntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang=Action"action!">PROC PrintBinary(CARD v)
CHAR ARRAY a(16)
BYTE i=[0]
Line 590 ⟶ 580:
Output for 9000 is 10001100101000
</pre>
 
=={{header|Ada}}==
 
<syntaxhighlight lang=Ada"ada">with ada.text_io; use ada.text_io;
procedure binary is
bit : array (0..1) of character := ('0','1');
Line 613 ⟶ 602:
Output for 9000 is 10001100101000
</pre>
 
=={{header|Aime}}==
<syntaxhighlight lang="aime">o_xinteger(2, 0);
o_byte('\n');
o_xinteger(2, 5);
Line 627 ⟶ 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'''<syntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #
 
printf((
Line 655 ⟶ 642:
+9000 => TFFFTTFFTFTFFF
</pre>
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">begin
% prints an integer in binary - the number must be greater than zero %
procedure printBinaryDigits( integer value n ) ;
begin
if n not = 0 then begin
printBinaryDigits( n div 2 );
writeon( if n rem 2 = 1 then "1" else "0" )
end
end binaryDigits ;
 
% prints an integer in binary - the number must not be negative %
procedure printBinary( integer value n ) ;
begin
if n = 0 then writeon( "0" )
else printBinaryDigits( n )
end printBinary ;
 
% test the printBinaryDigits procedure %
for i := 5, 50, 9000 do begin
write();
printBinary( i );
end
 
end.</syntaxhighlight>
=={{header|ALGOL-M}}==
<syntaxhighlight lang="algolm">begin
procedure writebin(n);
integer n;
Line 679 ⟶ 690:
110010
10001100101000</pre>
 
=={{header|APL}}==
Works in: [[Dyalog APL]]
 
A builtin function. Produces a boolean array.
<syntaxhighlight lang="apl">base2←2∘⊥⍣¯1</syntaxhighlight>
 
 
Line 690 ⟶ 700:
 
Produces a boolean array.
<syntaxhighlight lang="apl">base2 ← {((⌈2⍟⍵+1)⍴2)⊤⍵}</syntaxhighlight>
 
NOTE: Both versions above will yield an empty boolean array for 0.
Line 704 ⟶ 714:
1 0 0 0 1 1 0 0 1 0 1 0 0 0
</pre>
 
=={{header|ALGOL W}}==
<syntaxhighlight lang=algolw>begin
% prints an integer in binary - the number must be greater than zero %
procedure printBinaryDigits( integer value n ) ;
begin
if n not = 0 then begin
printBinaryDigits( n div 2 );
writeon( if n rem 2 = 1 then "1" else "0" )
end
end binaryDigits ;
 
% prints an integer in binary - the number must not be negative %
procedure printBinary( integer value n ) ;
begin
if n = 0 then writeon( "0" )
else printBinaryDigits( n )
end printBinary ;
 
% test the printBinaryDigits procedure %
for i := 5, 50, 9000 do begin
write();
printBinary( i );
end
 
end.</syntaxhighlight>
 
=={{header|AppleScript}}==
===Functional===
Line 737 ⟶ 720:
 
(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 -----------------------
 
-- showBin :: Int -> String
Line 839 ⟶ 822:
 
Or using:
<syntaxhighlight lang="applescript">-- showBin :: Int -> String
on showBin(n)
script binaryChar
Line 857 ⟶ 840:
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
Line 875 ⟶ 858:
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
Line 898 ⟶ 881:
intToBinary(50) & linefeed & ¬
intToBinary(9000) & linefeed</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM"arm Assemblyassembly">
 
/* ARM assembly Raspberry PI */
Line 1,066 ⟶ 1,048:
 
</syntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">print as.binary 5
print as.binary 50
print as.binary 9000</syntaxhighlight>
Line 1,077 ⟶ 1,058:
110010
10001100101000</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang=AutoHotkey"autohotkey">MsgBox % NumberToBinary(5) ;101
MsgBox % NumberToBinary(50) ;110010
MsgBox % NumberToBinary(9000) ;10001100101000
Line 1,089 ⟶ 1,069:
Return, Result
}</syntaxhighlight>
 
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
ConsoleWrite(IntToBin(50) & @CRLF)
 
Line 1,110 ⟶ 1,089:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">BEGIN {
print tobinary(0)
print tobinary(1)
print tobinary(5)
print tobinary(50)
Line 1,117 ⟶ 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
}</syntaxhighlight>
Line 1,136 ⟶ 1,106:
=={{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.
<syntaxhighlight lang="axe">Lbl BIN
.Axe supports 16-bit integers, so 16 digits are enough
L₁+16→P
Line 1,147 ⟶ 1,117:
Disp P,i
Return</syntaxhighlight>
 
=={{header|BaCon}}==
<syntaxhighlight lang="freebasic">' Binary digits
OPTION MEMTYPE int
INPUT n$
Line 1,157 ⟶ 1,126:
PRINT CHOP$(BIN$(VAL(n$)), "0", 1)
ENDIF</syntaxhighlight>
=={{header|Bash}}==
<syntaxhighlight lang="bash">
function to_binary () {
if [ $1 -ge 0 ]
then
val=$1
binary_digits=()
 
while [ $val -gt 0 ]; do
bit=$((val % 2))
quotient=$((val / 2))
binary_digits+=("${bit}")
val=$quotient
done
echo "${binary_digits[*]}" | rev
else
echo ERROR : "negative number"
exit 1
fi
}
 
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}}===
<syntaxhighlight lang=ApplesoftBasic"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 1,178:
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">
# DecToBin.bas
# BASIC256 1.1.4.0
Line 1,198:
 
==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic"> FOR num% = 0 TO 16
PRINT FN_tobase(num%, 2, 0)
NEXT
Line 1,216:
The above is a generic "Convert to any base" program.
Here is a faster "Convert to Binary" program:
<syntaxhighlight lang="bbcbasic">PRINT FNbinary(5)
PRINT FNbinary(50)
PRINT FNbinary(9000)
Line 1,228:
UNTIL N% = 0
=A$</syntaxhighlight>
 
==={{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}}===
Line 1,234 ⟶ 1,252:
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.
 
<syntaxhighlight lang="gwbasic">10 READ N
20 IF N < 0 THEN 70
30 GOSUB 100
Line 1,257 ⟶ 1,275:
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang=IS"is-BASICbasic">10 PRINT BIN$(50)
100 DEF BIN$(N)
110 LET N=ABS(INT(N)):LET B$=""
Line 1,267 ⟶ 1,285:
 
==={{header|QBasic}}===
<syntaxhighlight lang=QBasic"qbasic">FUNCTION BIN$ (N)
N = ABS(INT(N))
B$ = ""
Line 1,285 ⟶ 1,303:
 
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
Line 1,371 ⟶ 1,389:
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">FUNCTION BIN$ (N)
LET N = ABS(INT(N))
LET B$ = ""
Line 1,391 ⟶ 1,409:
END</syntaxhighlight>
 
==={{header|BashXBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang=BASH>
<syntaxhighlight lang="qbasic">PROGRAM "binardig"
function to_binary () {
VERSION "0.0000"
if [ $1 -ge 0 ]
then
val=$1
binary_digits=()
 
DECLARE FUNCTION Entry ()
while [ $val -gt 0 ]; do
bit=$((val % 2))
quotient=$((val / 2))
binary_digits+=("${bit}")
val=$quotient
done
echo "${binary_digits[*]}" | rev
else
echo ERROR : "negative number"
exit 1
fi
}
 
FUNCTION Entry ()
array=(5 50 9000)
DIM a[3]
for number in "${array[@]}"; do
a[0] = 5
echo $number " :> " $(to_binary $number)
a[1] = 50
done
a[2] = 9000
</syntaxhighlight>
{{out}}
FOR i = 0 TO 2
<pre>
PRINT FORMAT$ ("####", a[i]); " -> "; BIN$(a[i])
5 :> 1 0 1
NEXT i
50 :> 1 1 0 0 1 0
 
9000 :> 1 0 0 0 1 1 0 0 1 0 1 0 0 0
END FUNCTION
</pre>
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
Line 1,440 ⟶ 1,445:
)
exit /b</syntaxhighlight>
 
=={{header|bc}}==
{{trans|dc}}
<syntaxhighlight lang="bc">obase = 2
5
50
9000
quit</syntaxhighlight>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
let writebin(x) be
Line 1,470 ⟶ 1,473:
110010
10001100101000</pre>
 
=={{header|Beads}}==
<syntaxhighlight lang=Beads"beads">beads 1 program 'Binary Digits'
calc main_init
loop across:[5, 50, 9000] val:v
Line 1,481 ⟶ 1,483:
10001100101000
</pre>
 
=={{header|Befunge}}==
Reads the number to convert from standard input.
<syntaxhighlight lang="befunge">&>0\55+\:2%68>*#<+#8\#62#%/#2:_$>:#,_$@</syntaxhighlight>
{{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>
 
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}}==
<syntaxhighlight lang="bracmat"> ( dec2bin
= bit bits
. :?bits
Line 1,529 ⟶ 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.
 
<syntaxhighlight lang="bf">+[ Start with n=1 to kick off the loop
[>>++<< Set up {n 0 2} for divmod magic
[->+>- Then
Line 1,551 ⟶ 1,549:
++++++++++. Print a newline
[-]<+] Zero it then increment n and go again</syntaxhighlight>
 
=={{header|Burlesque}}==
<syntaxhighlight lang="burlesque">
blsq ) {5 50 9000}{2B!}m[uN
101
Line 1,559 ⟶ 1,556:
10001100101000
</syntaxhighlight>
 
=={{header|C}}==
===With bit level operations===
<syntaxhighlight lang=C"c">#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings
#define _CRT_NONSTDC_NO_DEPRECATE // enable old-gold POSIX names in MSVS
 
Line 1,682 ⟶ 1,678:
===With malloc and log10===
Converts int to a string.
<syntaxhighlight lang="c">#include <math.h>
#include <stdio.h>
#include <stdlib.h>
Line 1,731 ⟶ 1,727:
10010
10011</pre>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
 
class Program
Line 1,745 ⟶ 1,740:
}
}</syntaxhighlight>
Another version using dotnet 5<syntaxhighlight lang="csharp dotnet 5.0">using System;
using System.Text;
 
Line 1,765 ⟶ 1,760:
10001100101000
</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <bitset>
#include <iostream>
#include <limits>
Line 1,798 ⟶ 1,792:
</pre>
Shorter version using bitset
<syntaxhighlight lang="cpp">#include <iostream>
#include <bitset>
void printBits(int n) { // Use int like most programming languages.
Line 1,813 ⟶ 1,807:
} // for testing with n=0 printBits<32>(0);</syntaxhighlight>
Using >> operator. (1st example is 2.75x longer. Matter of taste.)
<syntaxhighlight lang="cpp">#include <iostream>
int main(int argc, char* argv[]) {
unsigned int in[] = {5, 50, 9000}; // Use int like most programming languages
Line 1,823 ⟶ 1,817:
</syntaxhighlight>
To be fair comparison with languages that doesn't declare a function like C++ main(). 3.14x shorter than 1st example.
<syntaxhighlight 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,832 ⟶ 1,826:
</syntaxhighlight>
Using bitwise operations with recursion.
<syntaxhighlight lang="cpp">
#include <iostream>
 
Line 1,851 ⟶ 1,845:
10001100101000
</pre>
 
=={{header|Ceylon}}==
<syntaxhighlight lang="ceylon"> shared void run() {
void printBinary(Integer integer) =>
Line 1,862 ⟶ 1,855:
printBinary(9k);
}</syntaxhighlight>
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">(Integer/toBinaryString 5)
(Integer/toBinaryString 50)
(Integer/toBinaryString 9000)</syntaxhighlight>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">binary = proc (n: int) returns (string)
bin: string := ""
while n > 0 do
Line 1,890 ⟶ 1,881:
50 -> 110010
9000 -> 10001100101000</pre>
 
=={{header|COBOL}}==
<syntaxhighlight lang=COBOL"cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. SAMPLE.
 
Line 1,920 ⟶ 1,910:
</syntaxhighlight>
Free-form, using a reference modifier to index into binary-number.
<syntaxhighlight lang="cobol">IDENTIFICATION DIVISION.
PROGRAM-ID. binary-conversion.
 
Line 1,947 ⟶ 1,937:
display binary-number.
stop run.</syntaxhighlight>
 
=={{header|CoffeeScript}}==
<syntaxhighlight lang="coffeescript">binary = (n) ->
new Number(n).toString(2)
console.log binary n for n in [5, 50, 9000]</syntaxhighlight>
 
=={{header|Common Lisp}}==
Just print the number with "~b":
<syntaxhighlight lang="lisp">(format t "~b" 5)
 
; or
 
(write 5 :base 2)</syntaxhighlight>
 
=={{header|Component Pascal}}==
BlackBox Component Builder
<syntaxhighlight lang="oberon2">
MODULE BinaryDigits;
IMPORT StdLog,Strings;
Line 1,987 ⟶ 1,974:
50:> 110010
9000:> 10001100101000</pre>
 
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
 
sub print_binary(n: uint32) is
Line 2,013 ⟶ 1,999:
110010
10001100101000</pre>
 
=={{header|Crystal}}==
{{trans|Ruby}}
Using an array
<syntaxhighlight lang="ruby">[5,50,9000].each do |n|
puts "%b" % n
end</syntaxhighlight>
Using a tuple
<syntaxhighlight lang="ruby">{5,50,9000}.each { |n| puts n.to_s(2) }</syntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
 
=={{header|D}}==
<syntaxhighlight lang="d">void main() {
import std.stdio;
 
Line 2,051 ⟶ 2,035:
1110
1111</pre>
 
=={{header|Dart}}==
<syntaxhighlight lang="dart">String binary(int n) {
if(n<0)
throw new IllegalArgumentException("negative numbers require 2s complement");
Line 2,078 ⟶ 2,061:
print(binary(0x123456789abcdef));
}</syntaxhighlight>
 
=={{header|dc}}==
<syntaxhighlight lang="dc">2o 5p 50p 9000p</syntaxhighlight>
 
{{out}}
Line 2,086 ⟶ 2,068:
110010
10001100101000</pre>
 
=={{header|Delphi}}==
<syntaxhighlight lang=Delphi"delphi">
program BinaryDigit;
{$APPTYPE CONSOLE}
Line 2,114 ⟶ 2,095:
9000: 10001100101000
</pre>
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">proc main() void:
writeln(5:b);
writeln(50:b);
writeln(9000:b);
corp</syntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
 
=={{header|dt}}==
<syntaxhighlight lang="dt">[dup 1 gt? [dup 2 % swap 2 / loop] swap do?] \loop def
 
[\loop doin rev \to-string map "" join] \bin def
 
[0 1 2 5 50 9000] \bin map " " join pl</syntaxhighlight>
{{out}}
<pre>0 1 10 101 110010 10001100101000</pre>
 
=={{header|Dyalect}}==
 
A default <code>ToString</code> method of type <code>Integer</code> is overridenoverridden and returns a binary representation of a number:
 
<syntaxhighlight lang="dyalect">func Integer.ToString() {
var s = ""
for x in 31^-1..0 {
Line 2,132 ⟶ 2,133:
print("5 == \(5), 50 = \(50), 1000 = \(9000)")</syntaxhighlight>
 
{{out}}
 
<pre>5 == 101, 50 = 110010, 1000 = 10001100101000</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
 
func$ bin num .
<syntaxhighlight lang=text>func to2 n . r$ .
if nb$ >= 0""
while callnum to2> n div 2 r$1
if n b$ = num mod 2 =& 0b$
r$num &= "0"num div 2
else.
return num & rb$ &= "1"
.
else
r$ = ""
.
.
print bin 5
func pr2 n . .
print bin 50
call to2 n r$
print bin 9000
if r$ = ""
</syntaxhighlight>
print "0"
{{out}}
else
print r$
.
.
call pr2 5
call pr2 50
call pr2 9000</syntaxhighlight>
 
<pre>
101
Line 2,170 ⟶ 2,158:
 
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">
;; primitive : (number->string number [base]) - default base = 10
 
Line 2,181 ⟶ 2,169:
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 56.0x :
<syntaxhighlight lang="elena">import system'routines;
import extensions;
 
public program()
{
new int[]{5,50,9000}.forEach::(n)
{
console.printLine(n.toString(2))
Line 2,203 ⟶ 2,231:
=={{header|Elixir}}==
Use <code>Integer.to_string</code> with a base of 2:
<syntaxhighlight lang=Elixir"elixir">
IO.puts Integer.to_string(5, 2)
</syntaxhighlight>
Or, using the pipe operator:
<syntaxhighlight lang=Elixir"elixir">
5 |> Integer.to_string(2) |> IO.puts
</syntaxhighlight>
<syntaxhighlight lang=Elixir"elixir">
[5,50,9000] |> Enum.each(fn n -> IO.puts Integer.to_string(n, 2) end)
</syntaxhighlight>
 
Line 2,219 ⟶ 2,247:
110010
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
Line 2,244 ⟶ 2,314:
9000: 10001100101000
</pre>
 
=={{header|Erlang}}==
With lists:map/2
<syntaxhighlight lang=erlang>lists:map( fun(N) -> io:fwrite("~.2B~n", [N]) end, [5, 50, 9000]). </syntaxhighlight>
<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 2,253 ⟶ 2,335:
 
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">function toBinary(integer i)
sequence s
s = {}
Line 2,268 ⟶ 2,350:
 
=== Functional/Recursive ===
<syntaxhighlight lang="euphoria">include std/math.e
include std/convert.e
 
Line 2,284 ⟶ 2,366:
printf(1, "%d\n", Bin(50))
printf(1, "%d\n", Bin(9000))</syntaxhighlight>
 
=={{header|F Sharp|F#}}==
By translating C#'s approach, using imperative coding style (inflexible):
<syntaxhighlight lang=FSharp"fsharp">open System
for i in [5; 50; 9000] do printfn "%s" <| Convert.ToString (i, 2)</syntaxhighlight>
 
Alternatively, by creating a function <code>printBin</code> which prints in binary (more flexible):
<syntaxhighlight lang=FSharp"fsharp">open System
 
// define the function
Line 2,304 ⟶ 2,385:
Or more idiomatic so that you can use it with any printf-style function and the <code>%a</code> format specifier (most flexible):
 
<syntaxhighlight lang=FSharp"fsharp">open System
open System.IO
 
Line 2,320 ⟶ 2,401:
10001100101000
</pre>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: io kernel math math.parser ;
 
5 >bin print
50 >bin print
9000 >bin print</syntaxhighlight>
 
=={{header|FALSE}}==
<syntaxhighlight lang="false">[0\10\[$1&'0+\2/$][]#%[$][,]#%]b:
 
5 b;!
Line 2,338 ⟶ 2,417:
110010
10001100101000</pre>
 
=={{header|FBSL}}==
<syntaxhighlight 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 2,353 ⟶ 2,431:
pause
</syntaxhighlight>
 
=={{header|FOCAL}}==
<syntaxhighlight lang=FOCAL"focal">01.10 S A=5;D 2
01.20 S A=50;D 2
01.30 S A=9000;D 2
Line 2,374 ⟶ 2,451:
110010
10001100101000</pre>
 
=={{header|Forth}}==
<syntaxhighlight lang="forth">\ Forth uses a system variable 'BASE' for number conversion
 
\ HEX is a standard word to change the value of base to 16
Line 2,404 ⟶ 2,480:
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"fortran">
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sun May 19 23:14:14
Line 2,466 ⟶ 2,541:
end program bits
</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang="pascal">program binaryDigits(input, output, stdErr);
{$mode ISO}
 
Line 2,494 ⟶ 2,568:
end.</syntaxhighlight>
Note, that the ISO compliant <tt>mod</tt> operation has to be used, which is ensured by the <tt>{$mode}</tt> directive in the second line.
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
' FreeBASIC v1.05.0 win64
Dim As String fmt = "#### -> &"
Line 2,514 ⟶ 2,587:
9000 -> 10001100101000
</pre>
 
=={{header|Frink}}==
The following all provide equivalent output. Input can be arbitrarily-large integers.
<syntaxhighlight lang="frink">
9000 -> binary
9000 -> base2
Line 2,523 ⟶ 2,595:
base[9000, 2]
</syntaxhighlight>
 
=={{header|FunL}}==
<syntaxhighlight lang="funl">for n <- [5, 50, 9000, 9000000000]
println( n, bin(n) )</syntaxhighlight>
 
Line 2,536 ⟶ 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"futhark">
fun main(x: i32): i64 =
loop (out = 0i64) = for i < 32 do
Line 2,549 ⟶ 2,619:
in out
</syntaxhighlight>
 
 
=={{header|FutureBasic}}==
The decimal to binary conversion can be handled with a simple function.
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
Line 2,577 ⟶ 2,645:
9000 = 10001100101000
</pre>
 
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=03e84768e6ee2af9b7664efa04fa6da8 Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim siBin As Short[] = [5, 50, 9000]
Dim siCount As Short
Line 2,596 ⟶ 2,662:
10001100101000
</pre>
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import (
Line 2,628 ⟶ 2,693:
1111
</pre>
 
=={{header|Groovy}}==
Solutions:
<syntaxhighlight lang="groovy">print '''
n binary
----- ---------------
Line 2,644 ⟶ 2,708:
50 110010
9000 10001100101000</pre>
 
=={{header|Haskell}}==
<syntaxhighlight 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 2,681 ⟶ 2,747:
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)
Line 2,711 ⟶ 2,777:
=={{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.
<syntaxhighlight lang=Icon"icon">procedure main()
every i := 5 | 50 | 255 | 1285 | 9000 do
write(i," = ",binary(i))
Line 2,740 ⟶ 2,806:
1285 = 10100000101
9000 = 10001100101000</pre>
 
=={{header|Idris}}==
<syntaxhighlight lang=Idris"idris">module Main
 
binaryDigit : Integer -> Char
Line 2,768 ⟶ 2,833:
10001100101000
</pre>
 
=={{header|J}}==
Generate a list of binary digits and use it to select characters from string '01'.
<syntaxhighlight lang=j> tobin=: -.&' '@":@#:
<syntaxhighlight lang="j"> tobin=: '01'{~#:
tobin 5
101
Line 2,777 ⟶ 2,842:
tobin 9000
10001100101000</syntaxhighlight>
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>
<syntaxhighlight 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">
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===
<syntaxhighlight lang="javascript">function toBinary(number) {
return new Number(number)
.toString(2);
Line 2,809 ⟶ 2,881:
The simplest showBinary (or showIntAtBase), using default digit characters, would use JavaScript's standard String.toString(base):
 
<syntaxhighlight lang=JavaScript"javascript">(() => {
"use strict";
 
Line 2,840 ⟶ 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:
 
<syntaxhighlight lang=JavaScript"javascript">(() => {
"use strict";
 
Line 2,900 ⟶ 2,972:
50 -> 一一〇〇一〇
9000 -> 一〇〇〇一一〇〇一〇一〇〇〇</pre>
 
=={{header|Joy}}==
<syntaxhighlight lang="joy">HIDEDEFINE bin == "" [pop 1 >] [[2 div "01" of] dip cons] while ["01" of] dip cons.
 
_ == [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</syntaxhighlight>
Using int2bin:
<syntaxhighlight lang=joy>0 setautoput
0 int2bin
5 int2bin
50 int2bin
9000 int2bin.</syntaxhighlight>
 
=={{header|jq}}==
<syntaxhighlight lang="jq">def binary_digits:
[ recurse( ./2 | floor; . > 0) % 2 ] | reverse | join("") ;
 
Line 2,925 ⟶ 2,990:
110010
10001100101000
 
=={{header|Julia}}==
{{works with|Julia|1.0}}
 
<syntaxhighlight lang="julia">using Printf
 
for n in (0, 5, 50, 9000)
Line 2,952 ⟶ 3,016:
50 → 00000000000000110010
9000 → 00000010001100101000</pre>
 
=={{header|K}}==
<syntaxhighlight lang="k"> tobin: ,/$2_vs
tobin' 5 50 9000
("101"
"110010"
"10001100101000")</syntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight lang=scala"kotlin">// 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))
}</syntaxhighlight>
 
{{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}
Line 2,998 ⟶ 3,069:
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}}==
<syntaxhighlight lang="lang5">'%b '__number_format set
[5 50 9000] [3 1] reshape .</syntaxhighlight>
{{out}}
Line 3,010 ⟶ 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:
<syntaxhighlight lang="lisp">
(: io format '"~.2B~n~.2B~n~.2B~n" (list 5 50 9000))
</syntaxhighlight>
 
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:
<syntaxhighlight lang="lisp">
(: lists foreach
(lambda (x)
Line 3,033 ⟶ 3,125:
10001100101000
</pre>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">for a = 0 to 16
print a;"=";dec2bin$(a)
next
Line 3,051 ⟶ 3,142:
end function
</syntaxhighlight>
 
=={{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"little Manman Computercomputer">
// Little Man Computer, for Rosetta Code.
// Read numbers from user and display them in binary.
Line 3,123 ⟶ 3,213:
900->1110000100
</pre>
 
 
=={{header|LLVM}}==
{{trans|C}}
<syntaxhighlight lang="llvm">; ModuleID = 'binary.c'
; source_filename = "binary.c"
; target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
Line 3,328 ⟶ 3,416:
10010
10011</pre>
 
=={{header|Locomotive Basic}}==
<syntaxhighlight lang="locobasic">10 PRINT BIN$(5)
20 PRINT BIN$(50)
30 PRINT BIN$(9000)</syntaxhighlight>
Line 3,337 ⟶ 3,424:
110010
10001100101000</pre>
 
=={{header|LOLCODE}}==
<syntaxhighlight lang=LOLCODE"lolcode">HAI 1.3
HOW IZ I DECIMULBINUR YR DECIMUL
I HAS A BINUR ITZ ""
Line 3,363 ⟶ 3,449:
=={{header|Lua}}==
===Lua - Iterative===
<syntaxhighlight lang=Lua"lua">function dec2bin (n)
local bin = ""
while n > 01 do
bin = n % 2 .. bin
n = math.floor(n / 2)
end
return n .. bin
end
 
Line 3,379 ⟶ 3,465:
110010
10001100101000</pre>
 
===Lua - Recursive===
{{works with|Lua|5.3+}}
<syntaxhighlight lang="lua">function-- dec2binfor Lua 5.1/5.2 use math.floor(n/2) instead of n>>1, bin)and n%2 instead of n&1
 
bin = (n&1) .. (bin or "") -- use n%2 instead of n&1 for Lua 5.1/5.2
function dec2bin(n)
return n>1 and dec2bin(n//2, bin) or bin -- use math.floor(n/2) instead of n//2 for Lua 5.1/5.2
return n>1 and dec2bin(n>>1)..(n&1) or n
end
 
Line 3,395 ⟶ 3,483:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
Module Checkit {
Form 90, 40
Line 3,463 ⟶ 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}}==
Line 3,469 ⟶ 3,587:
matches the binary representation of the input, e.g. <code>BINARY.(5)</code> is <code>101</code>.
 
<syntaxhighlight lang=MAD"mad"> NORMAL MODE IS INTEGER
INTERNAL FUNCTION(NUM)
Line 3,496 ⟶ 3,614:
 
=={{header|Maple}}==
<syntaxhighlight lang=Maple"maple">
> convert( 50, 'binary' );
110010
Line 3,502 ⟶ 3,620:
10001100101000
</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica"mathematica">StringJoin @@ ToString /@ IntegerDigits[50, 2] </syntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang=Matlab"matlab"> dec2bin(5)
dec2bin(50)
dec2bin(9000) </syntaxhighlight>
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 (
Line 3,525 ⟶ 3,640:
10001100101000
*/</syntaxhighlight>
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
-- MAXScript: Output decimal numbers from 0 to 16 as Binary : N.H. 2019
for k = 0 to 16 do
Line 3,572 ⟶ 3,686:
"10000"
</pre>
 
=={{header|Mercury}}==
<syntaxhighlight lang="mercury">:- module binary_digits.
:- interface.
 
Line 3,593 ⟶ 3,706:
 
=={{header|min}}==
{{works with|min|0.1937.30}}
<syntaxhighlight 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</syntaxhighlight>
{{out}}
<pre>0, 1, 10, 101, 110010, 10001100101000</pre>
<pre>
101
110010
10001100101000
</pre>
 
=={{header|MiniScript}}==
=== Iterative ===
<syntaxhighlight lang=MiniScript"miniscript">binary = function(n)
result = ""
while n
Line 3,629 ⟶ 3,735:
 
=== Recursive ===
<syntaxhighlight lang=MiniScript"miniscript">binary = function(n,result="")
if n == 0 then
if result == "" then return "0" else return result
Line 3,648 ⟶ 3,754:
0
</pre>
 
=={{header|mLite}}==
<syntaxhighlight 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)
Line 3,665 ⟶ 3,770:
> binary 9000;
"10001100101000"</pre>
 
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE Binary;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT Write,WriteLn,ReadChar;
Line 3,696 ⟶ 3,800:
ReadChar
END Binary.</syntaxhighlight>
 
=={{header|Modula-3}}==
<syntaxhighlight lang="modula3">MODULE Binary EXPORTS Main;
 
IMPORT IO, Fmt;
Line 3,714 ⟶ 3,817:
10010110
</pre>
 
=={{header|NetRexx}}==
<syntaxhighlight lang=NetRexx"netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 3,741 ⟶ 3,843:
9000: 10001100101000
</pre>
 
=={{header|NewLisp}}==
 
<syntaxhighlight lang=NewLisp"newlisp">
;;; Using the built-in "bits" function
;;; For integers up to 9,223,372,036,854,775,807
Line 3,766 ⟶ 3,867:
1110100000110010010010000001110101110000001101101111110011101110001010110010111100010111111001011011001110001111110000101011010010
</pre>
 
=={{header|Nickle}}==
Using the Nickle output radix operator:
Line 3,779 ⟶ 3,879:
> 9000 # 2
10001100101000</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">proc binDigits(x: BiggestInt, r: int): int =
## Calculates how many digits `x` has when each digit covers `r` bits.
result = 1
Line 3,824 ⟶ 3,923:
 
===Version using strformat===
<syntaxhighlight lang=Nim"nim">import strformat
 
for n in 0..15:
Line 3,846 ⟶ 3,945:
1110
1111</pre>
 
=={{header|Oberon-2}}==
<syntaxhighlight lang="oberon2">
MODULE BinaryDigits;
IMPORT Out;
Line 3,876 ⟶ 3,974:
101010
</pre>
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">class Binary {
function : Main(args : String[]) ~ Nil {
5->ToBinaryString()->PrintLine();
Line 3,891 ⟶ 3,988:
10001100101000
</pre>
 
=={{header|OCaml}}==
<syntaxhighlight 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]
Printf|> List.printfmap bin_of_int |> String.concat "%8s\n, " (bin_of_int|> d)print_endline</syntaxhighlight>
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 3,923 ⟶ 4,023:
ok
</pre>
 
=={{header|Ol}}==
<syntaxhighlight lang="scheme">
(print (number->string 5 2))
(print (number->string 50 2))
Line 3,936 ⟶ 4,035:
10001100101000
</pre>
 
=={{header|OxygenBasic}}==
The Assembly code uses block structures to minimise the use of labels.
<syntaxhighlight lang="oxygenbasic">
 
function BinaryBits(sys n) as string
Line 3,984 ⟶ 4,082:
print BinaryBits 0xaa 'result 10101010
</syntaxhighlight>
 
=={{header|Panda}}==
<syntaxhighlight lang="panda">0..15.radix:2 nl</syntaxhighlight>
{{out}}
<pre>0
Line 4,004 ⟶ 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.
<syntaxhighlight lang="pascal">program IntToBinTest;
{$MODE objFPC}
uses
Line 4,051 ⟶ 4,146:
Beware of the endianess of the constant.
I check performance with random Data.
<syntaxhighlight lang="pascal">
program IntToPcharTest;
uses
Line 4,171 ⟶ 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|Peloton}}==
<syntaxhighlight lang="sgml"><@ defbaslit>2</@>
 
<@ saybaslit>0</@>
Line 4,180 ⟶ 4,274:
<@ saybaslit>9000</@>
</syntaxhighlight>
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">for (5, 50, 9000) {
printf "%b\n", $_;
}</syntaxhighlight>
Line 4,190 ⟶ 4,283:
10001100101000
</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang=Phix"phix">(phixonline)-->
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%b\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%b\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">50</span><span style="color: #0000FF;">)</span>
Line 4,203 ⟶ 4,295:
10001100101000
</pre>
 
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti"phixmonti">def printBinary
"The decimal value " print dup print " should produce an output of " print
20 int>bit
Line 4,230 ⟶ 4,321:
 
Other solution
<syntaxhighlight lang=Phixmonti"phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/Binary_digits
by Galileo, 05/2022 #/
 
Line 4,255 ⟶ 4,346:
 
=== Press any key to exit ===</pre>
 
=={{header|PHP}}==
<syntaxhighlight lang="php"><?php
echo decbin(5);
echo decbin(50);
Line 4,265 ⟶ 4,355:
110010
10001100101000</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang=Picat"picat"> foreach(I in [5,50,900])
println(to_binary_string(I))
end.</syntaxhighlight>
Line 4,275 ⟶ 4,364:
110010
1110000100</pre>
 
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"picolisp">: (bin 5)
-> "101"
 
Line 4,286 ⟶ 4,373:
: (bin 9000)
-> "10001100101000"</syntaxhighlight>
 
=={{header|Piet}}==
 
Line 4,444 ⟶ 4,530:
 
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:
<syntaxhighlight lang="pli">put edit (25) (B);</syntaxhighlight>
{{out}}
<pre>Output: 0011001
</pre>
With leading zero suppression:
<syntaxhighlight lang="pli"> declare text character (50) initial (' ');
 
put string(text) edit (25) (b);
Line 4,464 ⟶ 4,549:
1111111111111111111111111111111
</pre>
 
=={{header|PL/M}}==
<syntaxhighlight lang="plm">100H:
 
/* CP/M BDOS CALL */
Line 4,506 ⟶ 4,590:
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.
<syntaxhighlight lang="powerbasic">
#COMPILE EXE
#DIM ALL
Line 4,527 ⟶ 4,610:
9000: 10001100101000 (00000000000000000010001100101000)
</pre>
 
=={{header|PowerShell}}==
{{libheader|Microsoft .NET Framework}}
<syntaxhighlight lang=PowerShell"powershell">@(5,50,900) | foreach-object { [Convert]::ToString($_,2) }</syntaxhighlight>
{{out}}
<pre>101
110010
1110000100</pre>
 
=={{header|Processing}}==
<syntaxhighlight lang="processing">println(Integer.toBinaryString(5)); // 101
println(Integer.toBinaryString(50)); // 110010
println(Integer.toBinaryString(9000)); // 10001100101000</syntaxhighlight>
Processing also has a binary() function, but this returns zero-padded results
<syntaxhighlight lang="processing">println(binary(5)); // 00000000000101
println(binary(50)); // 00000000110010
println(binary(9000)); // 10001100101000</syntaxhighlight>
 
=={{header|Prolog}}==
{{works with|SWI Prolog}}
{{works with|GNU Prolog}}
<syntaxhighlight lang="prolog">
binary(X) :- format('~2r~n', [X]).
main :- maplist(binary, [5,50,9000]), halt.
Line 4,556 ⟶ 4,636:
110010
10001100101000</pre>
 
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic"purebasic">If OpenConsole()
PrintN(Bin(5)) ;101
PrintN(Bin(50)) ;110010
Line 4,570 ⟶ 4,649:
110010
10001100101000</pre>
 
=={{header|Python}}==
===String.format() method===
{{works with|Python|3.X and 2.6+}}
<syntaxhighlight lang="python">>>> for i in range(16): print('{0:b}'.format(i))
 
0
Line 4,595 ⟶ 4,673:
===Built-in bin() function===
{{works with|Python|3.X and 2.6+}}
<syntaxhighlight lang="python">>>> for i in range(16): print(bin(i)[2:])
 
0
Line 4,614 ⟶ 4,692:
1111</syntaxhighlight>
Pre-Python 2.6:
<syntaxhighlight lang="python">>>> oct2bin = {'0': '000', '1': '001', '2': '010', '3': '011', '4': '100', '5': '101', '6': '110', '7': '111'}
>>> bin = lambda n: ''.join(oct2bin[octdigit] for octdigit in '%o' % n).lstrip('0') or '0'
>>> for i in range(16): print(bin(i))
Line 4,638 ⟶ 4,716:
 
Defined in terms of a more general '''showIntAtBase''' function:
<syntaxhighlight lang="python">'''Binary strings for integers'''
 
 
Line 4,741 ⟶ 4,819:
 
Or, using a more specialised function to decompose an integer to a list of boolean values:
<syntaxhighlight lang="python">'''Decomposition of an integer to a string of booleans.'''
 
 
Line 4,872 ⟶ 4,950:
50 -> 110010
9000 -> 10001100101000</pre>
 
=={{header|QB64}}==
<syntaxhighlight lang=QB64"qb64">
Print DecToBin$(5)
Print DecToBin$(50)
Line 4,926 ⟶ 5,003:
 
</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. )
Line 4,943 ⟶ 5,019:
A user-defined conversion might look something like this:
<syntaxhighlight lang="quackery">
[ [] swap
[ 2 /mod digit
Line 4,960 ⟶ 5,036:
10001100101000
</pre>
 
=={{header|R}}==
<syntaxhighlight lang="rsplus">
dec2bin <- function(num) {
ifelse(num == 0,
Line 4,981 ⟶ 5,056:
10001100101000
</pre>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
;; Option 1: binary formatter
Line 4,990 ⟶ 5,064:
(for ([i 16]) (displayln (number->string i 2)))
</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" line>say .fmt("%b") for 5, 50, 9000;</syntaxhighlight>
<pre>
101
Line 5,003 ⟶ 5,076:
Alternatively:
 
<syntaxhighlight lang="raku" line>say .base(2) for 5, 50, 9000;</syntaxhighlight>
<pre>101
110010
10001100101000</pre>
 
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
'Convert Integer to binary string
Print "bin 5 = ", bin$(5)
Line 5,016 ⟶ 5,088:
sleep 10
</syntaxhighlight>
 
=={{header|Red}}==
<syntaxhighlight lang=Red"red">Red []
 
foreach number [5 50 9000] [
Line 5,031 ⟶ 5,102:
9000 10001100101000
</pre>
 
=={{header|Retro}}==
<syntaxhighlight lang=Retro"retro">9000 50 5 3 [ binary putn cr decimal ] times</syntaxhighlight>
=={{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 5,040 ⟶ 5,130:
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).
<syntaxhighlight lang=REXX"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 5,062 ⟶ 5,152:
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.
<syntaxhighlight lang=REXX"rexx">/*REXX program to convert several decimal numbers to binary (or base 2). */
@.=; @.1= 0
@.2= 5
Line 5,077 ⟶ 5,167:
===concise version===
This version handles the case of zero a bit more obtusely, but concisely.
<syntaxhighlight lang=REXX"rexx">/*REXX program to convert several decimal numbers to binary (or base 2). */
@.=; @.1= 0
@.2= 5
Line 5,091 ⟶ 5,181:
===conforming version===
This REXX version conforms to the strict output requirements of this task (just show the binary output without any blanks).
<syntaxhighlight lang=REXX"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 5,116 ⟶ 5,206:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
see "Number to convert : "
give a
Line 5,130 ⟶ 5,220:
next
</syntaxhighlight>
 
=={{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}}==
<syntaxhighlight lang="ruby">[5,50,9000].each do |n|
puts "%b" % n
end</syntaxhighlight>
or
<syntaxhighlight lang="ruby">for n in [5,50,9000]
puts n.to_s(2)
end</syntaxhighlight>
Line 5,145 ⟶ 5,263:
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">input "Number to convert:";a
while 2^(n+1) < a
n = n + 1
Line 5,162 ⟶ 5,280:
<pre>Number to convert:?9000
10001100101000</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">fn main() {
for i in 0..8 {
println!("{:b}", i)
Line 5,178 ⟶ 5,295:
110
111</pre>
 
=={{header|S-lang}}==
<syntaxhighlight lang=S"s-lang">define int_to_bin(d)
{
variable m = 0x40000000, prn = 0, bs = "";
Line 5,205 ⟶ 5,321:
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>.
<syntaxhighlight lang="scala">scala> (5 toBinaryString)
res0: String = 101
 
Line 5,216 ⟶ 5,365:
scala> (9000 toBinaryString)
res2: String = 10001100101000</syntaxhighlight>
 
=={{header|Scheme}}==
<syntaxhighlight lang="scheme">(display (number->string 5 2)) (newline)
(display (number->string 50 2)) (newline)
(display (number->string 9000 2)) (newline)</syntaxhighlight>
 
=={{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.
 
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 5,255 ⟶ 5,442:
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)) :=
Line 5,273 ⟶ 5,475:
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">[5, 50, 9000].each { |n|
say n.as_bin;
}</syntaxhighlight>
Line 5,280 ⟶ 5,482:
110010
10001100101000</pre>
 
=={{header|Simula}}==
<syntaxhighlight lang="simula">BEGIN
 
PROCEDURE OUTINTBIN(N); INTEGER N;
Line 5,303 ⟶ 5,504:
10001100101000
</pre>
 
=={{header|SkookumScript}}==
 
<syntaxhighlight lang="javascript">println(5.binary)
println(50.binary)
println(9000.binary)</syntaxhighlight>
Or looping over a list of numbers:
<syntaxhighlight lang="javascript">{5 50 9000}.do[println(item.binary)]</syntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
 
=={{header|Smalltalk}}==
<syntaxhighlight lang="smalltalk">5 printOn: Stdout radix:2
50 printOn: Stdout radix:2
9000 printOn: Stdout radix:2</syntaxhighlight>
or:
<syntaxhighlight lang="smalltalk">#(5 50 9000) do:[:each | each printOn: Stdout radix:2. Stdout cr]</syntaxhighlight>
 
=={{header|SNOBOL4}}==
<syntaxhighlight lang="snobol4">
define('bin(n,r)') :(bin_end)
bin bin = le(n,0) r :s(return)
Line 5,340 ⟶ 5,538:
10001100101000
</pre>
 
=={{header|SNUSP}}==
<syntaxhighlight lang=SNUSP"snusp">
/recurse\
$,binary!\@\>?!\@/<@\.#
Line 5,349 ⟶ 5,546:
\?!#-?/+# mod2
</syntaxhighlight>
 
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">print (Int.fmt StringCvt.BIN 5 ^ "\n");
print (Int.fmt StringCvt.BIN 50 ^ "\n");
print (Int.fmt StringCvt.BIN 9000 ^ "\n");</syntaxhighlight>
 
=={{header|Swift}}==
<syntaxhighlight lang=Swift"swift">for num in [5, 50, 9000] {
println(String(num, radix: 2))
}</syntaxhighlight>
Line 5,364 ⟶ 5,559:
110010
10001100101000</pre>
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">proc num2bin num {
# Convert to _fixed width_ big-endian 32-bit binary
binary scan [binary format "I" $num] "B*" binval
Line 5,373 ⟶ 5,567:
}</syntaxhighlight>
Demonstrating:
<syntaxhighlight lang="tcl">for {set x 0} {$x < 16} {incr x} {
puts [num2bin $x]
}
Line 5,405 ⟶ 5,599:
<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>
Line 5,414 ⟶ 5,608:
50: 110010
9000: 10001100101000</pre>
 
=={{header|TI-83 BASIC}}==
Using Standard TI-83 BASIC
<syntaxhighlight lang="ti83b">PROGRAM:BINARY
:Disp "NUMBER TO"
:Disp "CONVERT:"
Line 5,437 ⟶ 5,630:
:Disp B</syntaxhighlight>
Alternate using a string to display larger numbers.
<syntaxhighlight lang="ti83b">PROGRAM:BINARY
:Input X
:" "→Str1
Line 5,447 ⟶ 5,640:
:Str1</syntaxhighlight>
Using the baseInput() "real(25," function from [http://www.detachedsolutions.com/omnicalc/ Omnicalc]
<syntaxhighlight lang="ti83b">PROGRAM:BINARY
:Disp "NUMBER TO"
:Disp "CONVERT"
Line 5,454 ⟶ 5,647:
 
More compact version:
<syntaxhighlight lang="ti83b">:Input "DEC: ",D
:" →Str1
:If not(D:"0→Str1
Line 5,467 ⟶ 5,660:
:Disp Str1
</syntaxhighlight>
 
=={{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 5,511 ⟶ 5,703:
 
=={{header|UNIX Shell}}==
Since POSIX does not specify local variables, make use of <code>set</code> for highest portability.
<syntaxhighlight 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</syntaxhighlight>
 
=={{header|VBA}}==
Line 5,541 ⟶ 5,737:
Places is useful for padding the return value with leading 0s (zeros).
 
<syntaxhighlight lang="vb">
Option Explicit
 
Line 5,588 ⟶ 5,784:
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.
<syntaxhighlight lang="vedit">repeat (ALL) {
#10 = Get_Num("Give a numeric value, -1 to end: ", STATLINE)
if (#10 < 0) { break }
Line 5,616 ⟶ 5,811:
10001100101000
</pre>
 
=={{header|Vim Script}}==
<syntaxhighlight lang="vim">function Num2Bin(n)
let n = a:n
let s = ""
Line 5,644 ⟶ 5,838:
110010
10001100101000</pre>
 
=={{header|Visual Basic}}==
{{works with|Visual Basic|VB6 Standard}}
<syntaxhighlight lang="vb">
Public Function Bin(ByVal l As Long) As String
Dim i As Long
Line 5,687 ⟶ 5,880:
110010
10001100101000</pre>
 
=={{header|Visual Basic .NET}}==
<syntaxhighlight lang="vbnet">Module Program
Sub Main
For Each number In {5, 50, 9000}
Line 5,700 ⟶ 5,892:
110010
10001100101000</pre>
 
=={{header|Visual FoxPro}}==
<syntaxhighlight lang="vfp">
*!* Binary Digits
CLEAR
Line 5,735 ⟶ 5,926:
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 5,740 ⟶ 6,013:
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"whitespace">
 
Line 5,783 ⟶ 6,056:
It was generated from the following pseudo-Assembly.
 
<syntaxhighlight lang="asm">push 0
; Increment indefinitely.
0:
Line 5,816 ⟶ 6,089:
pop
ret</syntaxhighlight>
 
=={{header|Vlang}}==
<syntaxhighlight lang=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|Wortel}}==
Using JavaScripts buildin toString method on the Number object, the following function takes a number and returns a string with the binary representation:
<syntaxhighlight lang="wortel">\.toString 2
; the following function also casts the string to a number
^(@+ \.toString 2)</syntaxhighlight>
To output to the console:
<syntaxhighlight lang="wortel">@each ^(console.log \.toString 2) [5 50 900]</syntaxhighlight>
Outputs: <pre>
101
110010
1110000100</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<syntaxhighlight lang=ecmascript"wren">import "./fmt" for Fmt
System.print("Converting to binary:")
Line 5,894 ⟶ 6,118:
=={{header|X86 Assembly}}==
Translation of XPL0. Assemble with tasm, tlink /t
<syntaxhighlight lang="asm"> .model tiny
.code
.486
Line 5,930 ⟶ 6,154:
10001100101000
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang=XPL0"xpl0">include c:\cxpl\codes; \intrinsic code declarations
 
proc BinOut(N); \Output N in binary
Line 5,967 ⟶ 6,190:
100000010100001
</pre>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">dim a(3)
a(0) = 5
a(1) = 50
Line 5,978 ⟶ 6,200:
next i
end</syntaxhighlight>
 
=={{header|Z80 Assembly}}==
{{trans|8086 Assembly}}
 
<syntaxhighlight lang="z80">org &8000
PrintChar equ &BB5A ;syscall - prints accumulator to Amstrad CPC's screen
 
Line 6,058 ⟶ 6,279:
 
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
Line 6,104 ⟶ 6,325:
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}}==
<syntaxhighlight 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$
2,114

edits