Binary digits: Difference between revisions

m
syntax highlighting fixup automation
(→‎{{header|Commodore BASIC}}: make subroutine more general (create string, no print), use READ loop with DATA for demo, add comment on FOR STEP 0 loop.)
m (syntax highlighting fixup automation)
Line 17:
 
=={{header|0815}}==
<langsyntaxhighlight lang=0815>}:r:|~ Read numbers in a loop.
}:b: Treat the queue as a stack and
<:2:= accumulate the binary digits
Line 28:
^:p:
<:a:~$ Output a newline.
^:r:</langsyntaxhighlight>
 
{{out}}
Line 34:
Note that 0815 reads numeric input in hexadecimal.
 
<langsyntaxhighlight lang=bash>echo -e "5\n32\n2329" | 0815 bin.0
101
110010
10001100101001</langsyntaxhighlight>
 
=={{header|11l}}==
<langsyntaxhighlight lang=11l>L(n) [0, 5, 50, 9000]
print(‘#4 = #.’.format(n, bin(n)))</langsyntaxhighlight>
{{out}}
<pre>
Line 51:
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang=360asm>* Binary digits 27/08/2015
BINARY CSECT
USING BINARY,R12
Line 93:
CBIN DC CL32' ' binary value
YREGS
END BINARY</langsyntaxhighlight>
{{out}}
<pre>
Line 122:
strout = $cb1e
</pre>
<langsyntaxhighlight lang=6502asm>
; C64 - Binary digits
; http://rosettacode.org/wiki/Binary_digits
Line 213:
binstr .repeat 16, $00 ; reserve 16 bytes for the binary digits
.byte $0d, $00 ; newline + null terminator
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 230:
 
=={{header|8080 Assembly}}==
<langsyntaxhighlight lang=8080asm>bdos: equ 5h ; CP/M system call
puts: equ 9h ; Print string
org 100h
Line 261:
jmp binlp ; Otherwise, do next bit
binstr: db '0000000000000000' ; Placeholder for string
binend: db 13,10,'$' ; end with \r\n </langsyntaxhighlight>
 
{{out}}
Line 272:
 
=={{header|8086 Assembly}}==
<langsyntaxhighlight lang=asm> .model small
.stack 1024
.data
Line 356:
pop ax
ret
PrintBinary_NoLeadingZeroes endp</langsyntaxhighlight>
 
=={{header|8th}}==
<langsyntaxhighlight lang=forth>
2 base drop
#50 . cr
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 370:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<langsyntaxhighlight lang=AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program binarydigit.s */
Line 524:
.include "../includeARM64.inc"
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 534:
 
=={{header|ACL2}}==
<langsyntaxhighlight lang=Lisp>(include-book "arithmetic-3/top" :dir :system)
 
(defun bin-string-r (x)
Line 548:
(if (zp x)
"0"
(bin-string-r x)))</langsyntaxhighlight>
 
=={{header|Action!}}==
<langsyntaxhighlight lang=Action!>PROC PrintBinary(CARD v)
CHAR ARRAY a(16)
BYTE i=[0]
Line 581:
PutE()
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Binary_digits.png Screenshot from Atari 8-bit computer]
Line 593:
=={{header|Ada}}==
 
<langsyntaxhighlight lang=Ada>with ada.text_io; use ada.text_io;
procedure binary is
bit : array (0..1) of character := ('0','1');
Line 605:
put_line ("Output for" & test'img & " is " & bin_image (test));
end loop;
end binary;</langsyntaxhighlight>
 
{{out}}
Line 615:
 
=={{header|Aime}}==
<langsyntaxhighlight lang=aime>o_xinteger(2, 0);
o_byte('\n');
o_xinteger(2, 5);
Line 621:
o_xinteger(2, 50);
o_byte('\n');
o_form("/x2/\n", 9000);</langsyntaxhighlight>
{{out}}
<pre>0
Line 632:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.3.3 algol68g-2.3.3].}}
{{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 645:
50, " => ", []BOOL(BIN 50)[bits width-6+1:], new line,
9000, " => ", []BOOL(BIN 9000)[bits width-14+1:], new line
))</langsyntaxhighlight>
{{out}}
<pre>
Line 657:
 
=={{header|ALGOL-M}}==
<langsyntaxhighlight lang=algolm>begin
procedure writebin(n);
integer n;
Line 674:
writebin(50);
writebin(9000);
end</langsyntaxhighlight>
{{out}}
<pre>101
Line 684:
 
A builtin function. Produces a boolean array.
<syntaxhighlight lang =apl>base2←2∘⊥⍣¯1</langsyntaxhighlight>
 
 
Line 690:
 
Produces a boolean array.
<langsyntaxhighlight lang=apl>base2 ← {((⌈2⍟⍵+1)⍴2)⊤⍵}</langsyntaxhighlight>
 
NOTE: Both versions above will yield an empty boolean array for 0.
Line 706:
 
=={{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 729:
end
 
end.</langsyntaxhighlight>
 
=={{header|AppleScript}}==
Line 737:
 
(The generic showIntAtBase here, which allows us to specify the digit set used (e.g. upper or lower case in hex, or different regional or other digit sets generally), is a rough translation of Haskell's Numeric.showintAtBase)
<langsyntaxhighlight lang=applescript>---------------------- BINARY STRING -----------------------
 
-- showBin :: Int -> String
Line 833:
on unlines(xs)
intercalate(linefeed, xs)
end unlines</langsyntaxhighlight>
<pre>5 -> 101
50 -> 110010
Line 839:
 
Or using:
<langsyntaxhighlight lang=applescript>-- showBin :: Int -> String
on showBin(n)
script binaryChar
Line 847:
end script
showIntAtBase(2, binaryChar, n, "")
end showBin</langsyntaxhighlight>
{{Out}}
<pre>5 -> 一〇一
Line 857:
At its very simplest, an AppleScript solution would look something like this:
 
<langsyntaxhighlight lang=applescript>on intToBinary(n)
set binary to (n mod 2 div 1) as text
set n to n div 2
Line 871:
intToBinary(5) & linefeed & ¬
intToBinary(50) & linefeed & ¬
intToBinary(9000) & linefeed</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang=applescript>on intToBinary(n)
set binary to ""
repeat
Line 897:
intToBinary(5) & linefeed & ¬
intToBinary(50) & linefeed & ¬
intToBinary(9000) & linefeed</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<langsyntaxhighlight lang=ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 1,065:
.Ls_magic_number_10: .word 0x66666667
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang=rebol>print as.binary 5
print as.binary 50
print as.binary 9000</langsyntaxhighlight>
{{out}}
Line 1,079:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang=AutoHotkey>MsgBox % NumberToBinary(5) ;101
MsgBox % NumberToBinary(50) ;110010
MsgBox % NumberToBinary(9000) ;10001100101000
Line 1,088:
Result := (InputNumber & 1) . Result, InputNumber >>= 1
Return, Result
}</langsyntaxhighlight>
 
=={{header|AutoIt}}==
<langsyntaxhighlight lang=autoit>
ConsoleWrite(IntToBin(50) & @CRLF)
 
Line 1,107:
Return $r
EndFunc ;==>IntToBin
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
<langsyntaxhighlight lang=awk>BEGIN {
print tobinary(5)
print tobinary(50)
Line 1,132:
}
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 1,146:
End
Disp P,i
Return</langsyntaxhighlight>
 
=={{header|BaCon}}==
<langsyntaxhighlight lang=freebasic>' Binary digits
OPTION MEMTYPE int
INPUT n$
Line 1,156:
ELSE
PRINT CHOP$(BIN$(VAL(n$)), "0", 1)
ENDIF</langsyntaxhighlight>
 
=={{header|BASIC}}==
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight lang=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,170:
7 NEXT N1
8 PRINT B$
9 RETURN</langsyntaxhighlight>
{{out}}
<pre>101
Line 1,178:
 
==={{header|BASIC256}}===
<langsyntaxhighlight lang=basic256>
# DecToBin.bas
# BASIC256 1.1.4.0
Line 1,189:
print a[i] + chr(9) + toRadix(a[i],2) # radix (decimal, base2)
next i
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,198:
 
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang=bbcbasic> FOR num% = 0 TO 16
PRINT FN_tobase(num%, 2, 0)
NEXT
Line 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 1,227:
N% = N% >>> 1 : REM BBC Basic prior to V5 can use N% = N% DIV 2
UNTIL N% = 0
=A$</langsyntaxhighlight>
 
==={{header|Commodore BASIC}}===
Line 1,234:
Note the <tt>FOR N1 =</tt> ... <tt>TO 0 STEP 0</tt> idiom; the zero step means that the variable is not modified by BASIC, so it's up to the code inside the loop to eventually set <tt>N1</tt> to 0 so that the loop terminates – like a C <tt>for</tt> loop with an empty third clause. After the initialization, it's essentially a "while N1 is not 0" loop, but Commodore BASIC originally didn't have <b>while</b> loops (<tt>DO WHILE</tt> ... <tt>LOOP</tt> was added in BASIC 3.5). The alternative would be a <tt>GOTO</tt>, but the <tt>FOR</tt> loop lends more structure.
 
<langsyntaxhighlight lang=gwbasic>10 READ N
20 IF N < 0 THEN 70
30 GOSUB 100
Line 1,247:
130 : N1 = INT(N1/2)
140 NEXT N1
150 RETURN</langsyntaxhighlight>
 
{{Out}}
Line 1,257:
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight lang=IS-BASIC>10 PRINT BIN$(50)
100 DEF BIN$(N)
110 LET N=ABS(INT(N)):LET B$=""
Line 1,264:
150 LOOP WHILE N>0
160 LET BIN$=B$
170 END DEF</langsyntaxhighlight>
 
==={{header|QBasic}}===
<langsyntaxhighlight lang=QBasic>FUNCTION BIN$ (N)
N = ABS(INT(N))
B$ = ""
Line 1,280:
PRINT USING fmt$; 5; BIN$(5)
PRINT USING fmt$; 50; BIN$(50)
PRINT USING fmt$; 9000; BIN$(9000)</langsyntaxhighlight>
 
==={{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.
<langsyntaxhighlight 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,368:
 
999 PRINT 0 REM zero is the one time we DO want to print a leading zero
END</langsyntaxhighlight>
 
==={{header|True BASIC}}===
<langsyntaxhighlight lang=qbasic>FUNCTION BIN$ (N)
LET N = ABS(INT(N))
LET B$ = ""
Line 1,389:
PRINT USING "####": 9000;
PRINT " -> "; BIN$(9000)
END</langsyntaxhighlight>
 
=={{header|Bash}}==
<langsyntaxhighlight lang=BASH>
function to_binary () {
if [ $1 -ge 0 ]
Line 1,416:
echo $number " :> " $(to_binary $number)
done
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,426:
=={{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.
<langsyntaxhighlight lang=dos>@echo off
:num2bin IntVal [RtnVar]
setlocal enableDelayedExpansion
Line 1,439:
if "%~2" neq "" (set %~2=%rtn%) else echo %rtn%
)
exit /b</langsyntaxhighlight>
 
=={{header|bc}}==
{{trans|dc}}
<langsyntaxhighlight lang=bc>obase = 2
5
50
9000
quit</langsyntaxhighlight>
 
=={{header|BCPL}}==
<langsyntaxhighlight lang=bcpl>get "libhdr"
 
let writebin(x) be
Line 1,465:
writebin(50)
writebin(9000)
$)</langsyntaxhighlight>
{{out}}
<pre>101
Line 1,472:
 
=={{header|Beads}}==
<langsyntaxhighlight lang=Beads>beads 1 program 'Binary Digits'
calc main_init
loop across:[5, 50, 9000] val:v
log to_str(v, base:2)</langsyntaxhighlight>
{{out}}
<pre>101
Line 1,484:
=={{header|Befunge}}==
Reads the number to convert from standard input.
<langsyntaxhighlight lang=befunge>&>0\55+\:2%68>*#<+#8\#62#%/#2:_$>:#,_$@</langsyntaxhighlight>
{{out}}
<pre>9000
Line 1,492:
 
A BQNcrate idiom which returns the digits as a boolean array.
<langsyntaxhighlight lang=bqn>Bin ← 2{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}
 
Bin¨5‿50‿9000</langsyntaxhighlight><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 ⟩ ⟩</langsyntaxhighlight>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang=bracmat> ( dec2bin
= bit bits
. :?bits
Line 1,513:
& put$(str$(!dec ":\n" dec2bin$!dec \n\n))
)
;</langsyntaxhighlight>
{{out}}
<pre>0:
Line 1,534:
This is almost an exact duplicate of [[Count in octal#Brainf***]]. It outputs binary numbers until it is forced to terminate or the counter overflows to 0.
 
<langsyntaxhighlight lang=bf>+[ Start with n=1 to kick off the loop
[>>++<< Set up {n 0 2} for divmod magic
[->+>- Then
Line 1,550:
<[[-]<] 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===
<langsyntaxhighlight lang=C>#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings
#define _CRT_NONSTDC_NO_DEPRECATE // enable old-gold POSIX names in MSVS
 
Line 1,668:
return EXIT_SUCCESS;
}
</syntaxhighlight>
</lang>
{{output}}
<pre>itoa: 5 decimal = 101 binary
Line 1,682:
===With malloc and log10===
Converts int to a string.
<langsyntaxhighlight lang=c>#include <math.h>
#include <stdio.h>
#include <stdlib.h>
Line 1,708:
ret[bits] = '\0';
return ret;
}</langsyntaxhighlight>
 
{{out}}
Line 1,733:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang=csharp>using System;
 
class Program
Line 1,744:
}
}
}</langsyntaxhighlight>
Another version using dotnet 5<langsyntaxhighlight lang=csharp dotnet 5.0>using System;
using System.Text;
 
Line 1,758:
Console.WriteLine(ToBinary(5));
Console.WriteLine(ToBinary(50));
Console.WriteLine(ToBinary(9000));</langsyntaxhighlight>
{{out}}
<pre>
Line 1,767:
 
=={{header|C++}}==
<langsyntaxhighlight lang=cpp>#include <bitset>
#include <iostream>
#include <limits>
Line 1,789:
print_bin(9000);
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,798:
</pre>
Shorter version using bitset
<langsyntaxhighlight lang=cpp>#include <iostream>
#include <bitset>
void printBits(int n) { // Use int like most programming languages.
Line 1,811:
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,821:
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,830:
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,844:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,853:
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang=ceylon> shared void run() {
void printBinary(Integer integer) =>
Line 1,861:
printBinary(50);
printBinary(9k);
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang=clojure>(Integer/toBinaryString 5)
(Integer/toBinaryString 50)
(Integer/toBinaryString 9000)</langsyntaxhighlight>
 
=={{header|CLU}}==
<langsyntaxhighlight lang=clu>binary = proc (n: int) returns (string)
bin: string := ""
while n > 0 do
Line 1,885:
stream$putl(po, int$unparse(test) || " -> " || binary(test))
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>5 -> 101
Line 1,892:
 
=={{header|COBOL}}==
<langsyntaxhighlight lang=COBOL> IDENTIFICATION DIVISION.
PROGRAM-ID. SAMPLE.
 
Line 1,918:
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,946:
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,980:
END Do;
END BinaryDigits.
</syntaxhighlight>
</lang>
Execute: ^Q BinaryDigits.Do <br/>
{{out}}
Line 1,989:
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang=cowgol>include "cowgol.coh";
 
sub print_binary(n: uint32) is
Line 2,008:
print_binary(5);
print_binary(50);
print_binary(9000);</langsyntaxhighlight>
{{out}}
<pre>101
Line 2,017:
{{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
Line 2,028:
 
=={{header|D}}==
<langsyntaxhighlight lang=d>void main() {
import std.stdio;
 
foreach (immutable i; 0 .. 16)
writefln("%b", i);
}</langsyntaxhighlight>
{{out}}
<pre>0
Line 2,053:
 
=={{header|Dart}}==
<langsyntaxhighlight lang=dart>String binary(int n) {
if(n<0)
throw new IllegalArgumentException("negative numbers require 2s complement");
Line 2,077:
// fails due to precision limit
print(binary(0x123456789abcdef));
}</langsyntaxhighlight>
 
=={{header|dc}}==
<syntaxhighlight lang =dc>2o 5p 50p 9000p</langsyntaxhighlight>
 
{{out}}
Line 2,088:
 
=={{header|Delphi}}==
<langsyntaxhighlight lang=Delphi>
program BinaryDigit;
{$APPTYPE CONSOLE}
Line 2,107:
writeln(' 50: ',IntToBinStr(50));
writeln('9000: '+IntToBinStr(9000));
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,119:
A default <code>ToString</code> method of type <code>Integer</code> is overriden and returns a binary representation of a number:
 
<langsyntaxhighlight lang=dyalect>func Integer.ToString() {
var s = ""
for x in 31^-1..0 {
Line 2,131:
}
print("5 == \(5), 50 = \(50), 1000 = \(9000)")</langsyntaxhighlight>
 
{{out}}
Line 2,139:
=={{header|EasyLang}}==
 
<syntaxhighlight lang=text>func to2 n . r$ .
if n > 0
call to2 n div 2 r$
Line 2,161:
call pr2 5
call pr2 50
call pr2 9000</langsyntaxhighlight>
 
<pre>
Line 2,170:
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang=scheme>
;; primitive : (number->string number [base]) - default base = 10
 
Line 2,180:
110010
10001100101000
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 5.0 :
<langsyntaxhighlight lang=elena>import system'routines;
import extensions;
 
Line 2,193:
console.printLine(n.toString(2))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,203:
=={{header|Elixir}}==
Use <code>Integer.to_string</code> with a base of 2:
<langsyntaxhighlight lang=Elixir>
IO.puts Integer.to_string(5,2)
</syntaxhighlight>
</lang>
Or, using the pipe operator:
<langsyntaxhighlight lang=Elixir>
5 |> Integer.to_string(2) |> IO.puts
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang=Elixir>
[5,50,9000] |> Enum.each(fn n -> IO.puts Integer.to_string(n,2) end)
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,222:
 
=={{header|Epoxy}}==
<langsyntaxhighlight lang=epoxy>fn bin(a,b:true)
var c:""
while a>0 do
Line 2,237:
iter Value of List do
log(Value+": "+bin(Value,false))
cls</langsyntaxhighlight>
{{out}}
<pre>
Line 2,246:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang=erlang>lists:map( fun(N) -> io:fwrite("~.2B~n", [N]) end, [5, 50, 9000]). </langsyntaxhighlight>
{{out}}
<pre>101
Line 2,253:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang=euphoria>function toBinary(integer i)
sequence s
s = {}
Line 2,265:
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 2,283:
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 lang=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 lang=FSharp>open System
 
// define the function
Line 2,300:
// 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 lang=FSharp>open System
open System.IO
 
Line 2,313:
// use it with printfn with %a
[5; 50; 9000]
|> List.iter (printfn "binary: %a" bin)</langsyntaxhighlight>
Output (either version):
<pre>
Line 2,322:
 
=={{header|Factor}}==
<langsyntaxhighlight lang=factor>USING: io kernel math math.parser ;
 
5 >bin print
50 >bin print
9000 >bin print</langsyntaxhighlight>
 
=={{header|FALSE}}==
<langsyntaxhighlight lang=false>[0\10\[$1&'0+\2/$][]#%[$][,]#%]b:
 
5 b;!
50 b;!
9000 b;!</langsyntaxhighlight>
{{out}}
<pre>101
Line 2,340:
 
=={{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 2,352:
 
pause
</syntaxhighlight>
</lang>
 
=={{header|FOCAL}}==
<langsyntaxhighlight lang=FOCAL>01.10 S A=5;D 2
01.20 S A=50;D 2
01.30 S A=9000;D 2
Line 2,369:
02.50 I (-BX)2.4;T !;R
02.60 I (-BD(BX))2.7;T "0";R
02.70 T "1"</langsyntaxhighlight>
{{out}}
<pre>101
Line 2,376:
 
=={{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 2,395:
decimal
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,407:
=={{header|Fortran}}==
Please find compilation instructions and the example run at the start of the FORTRAN90 source that follows. Thank you.
<langsyntaxhighlight lang=FORTRAN>
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sun May 19 23:14:14
Line 2,465:
 
end program bits
</syntaxhighlight>
</lang>
 
=={{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 2,492:
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}}==
<langsyntaxhighlight lang=freebasic>
' FreeBASIC v1.05.0 win64
Dim As String fmt = "#### -> &"
Line 2,506:
Sleep
End
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,517:
=={{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 2,541:
We produce the binary number as a 64-bit integer whose digits are all 0s and 1s - this is because Futhark does not have any way to print, nor strings for that matter.
 
<langsyntaxhighlight lang=Futhark>
fun main(x: i32): i64 =
loop (out = 0i64) = for i < 32 do
Line 2,548:
in out
in out
</syntaxhighlight>
</lang>
 
 
=={{header|FutureBasic}}==
The decimal to binary conversion can be handled with a simple function.
<langsyntaxhighlight lang=futurebasic>
include "NSLog.incl"
 
Line 2,570:
 
HandleEvents
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 2,581:
=={{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 2,589:
Next
 
End</langsyntaxhighlight>
{{out}}
<pre>
Line 2,598:
 
=={{header|Go}}==
<langsyntaxhighlight lang=go>package main
 
import (
Line 2,608:
fmt.Printf("%b\n", i)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,631:
=={{header|Groovy}}==
Solutions:
<langsyntaxhighlight lang=groovy>print '''
n binary
----- ---------------
Line 2,637:
[5, 50, 9000].each {
printf('%5d %15s\n', it, Integer.toBinaryString(it))
}</langsyntaxhighlight>
{{out}}
<pre> n binary
Line 2,646:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang=haskell>import Data.List
import Numeric
import Text.Printf
Line 2,669:
main = do
putStrLn $ printf "%4s %14s %14s" "N" "toBin" "toBin1"
mapM_ printToBin [5, 50, 9000]</langsyntaxhighlight>
{{out}}
<pre>
Line 2,681:
and in terms of first and swap, we could also write this as:
 
<langsyntaxhighlight lang=haskell>import Data.Bifunctor (first)
import Data.List (unfoldr)
import Data.Tuple (swap)
Line 2,703:
)
)
[5, 50, 9000]</langsyntaxhighlight>
{{Out}}
<pre>5 -> 101
Line 2,711:
=={{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 lang=Icon>procedure main()
every i := 5 | 50 | 255 | 1285 | 9000 do
write(i," = ",binary(i))
Line 2,733:
}
return reverse(trim(b,"0")) # nothing extraneous
end</langsyntaxhighlight>
{{out}}
<pre>5 = 101
Line 2,742:
 
=={{header|Idris}}==
<langsyntaxhighlight lang=Idris>module Main
 
binaryDigit : Integer -> Char
Line 2,760:
putStrLn (binaryString 50)
putStrLn (binaryString 9000)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,770:
 
=={{header|J}}==
<langsyntaxhighlight lang=j> tobin=: -.&' '@":@#:
tobin 5
101
Line 2,776:
110010
tobin 9000
10001100101000</langsyntaxhighlight>
Algorithm: Remove spaces from the character list which results from formatting the binary list which represents the numeric argument.
 
Line 2,782:
 
=={{header|Java}}==
<langsyntaxhighlight lang=java>public class Main {
public static void main(String[] args) {
System.out.println(Integer.toBinaryString(5));
Line 2,788:
System.out.println(Integer.toBinaryString(9000));
}
}</langsyntaxhighlight>
{{out}}
<pre>101
Line 2,796:
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight lang=javascript>function toBinary(number) {
return new Number(number)
.toString(2);
Line 2,804:
// alert() in a browser, wscript.echo in WSH, etc.
print(toBinary(demoValues[i]));
}</langsyntaxhighlight>
 
===ES6===
The simplest showBinary (or showIntAtBase), using default digit characters, would use JavaScript's standard String.toString(base):
 
<langsyntaxhighlight lang=JavaScript>(() => {
"use strict";
 
Line 2,832:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>5 -> 101
Line 2,840:
Or, if we need more flexibility with the set of digits used, we can write a version of showIntAtBase which takes a more specific Int -> Char function as as an argument. This one is a rough translation of Haskell's Numeric.showIntAtBase:
 
<langsyntaxhighlight lang=JavaScript>(() => {
"use strict";
 
Line 2,895:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>5 -> 一〇一
Line 2,902:
 
=={{header|Joy}}==
<langsyntaxhighlight lang=joy>HIDE
_ == [null] [pop] [2 div swap] [48 + putch] linrec
IN
int2bin == [null] [48 + putch] [_] ifte '\n putch
END</langsyntaxhighlight>
Using int2bin:
<langsyntaxhighlight lang=joy>0 setautoput
0 int2bin
5 int2bin
50 int2bin
9000 int2bin.</langsyntaxhighlight>
 
=={{header|jq}}==
<langsyntaxhighlight lang=jq>def binary_digits:
[ recurse( ./2 | floor; . > 0) % 2 ] | reverse | join("") ;
 
# The task:
(5, 50, 9000) | binary_digits</langsyntaxhighlight>
{{Out}}
$ jq -n -r -f Binary_digits.jq
Line 2,929:
{{works with|Julia|1.0}}
 
<langsyntaxhighlight lang=julia>using Printf
 
for n in (0, 5, 50, 9000)
Line 2,939:
for n in (0, 5, 50, 9000)
@printf("%6i → %s\n", n, string(n, base=2, pad=20))
end</langsyntaxhighlight>
 
{{out}}
Line 2,954:
 
=={{header|K}}==
<langsyntaxhighlight lang=k> tobin: ,/$2_vs
tobin' 5 50 9000
("101"
"110010"
"10001100101000")</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang=scala>// version 1.0.5-2
 
fun main(args: Array<String>) {
val numbers = intArrayOf(5, 50, 9000)
for (number in numbers) println("%4d".format(number) + " -> " + Integer.toBinaryString(number))
}</langsyntaxhighlight>
 
{{out}}
Line 2,976:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang=scheme>
{def dec2bin
{lambda {:dec}
Line 2,999:
9000 -> 10001100101000
 
</syntaxhighlight>
</lang>
 
=={{header|Lang5}}==
<langsyntaxhighlight lang=lang5>'%b '__number_format set
[5 50 9000] [3 1] reshape .</langsyntaxhighlight>
{{out}}
<pre>[
Line 3,014:
 
If one is simple printing the results and doesn't need to use them (e.g., assign them to any variables, etc.), this is very concise:
<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 3,026:
(list (: erlang integer_to_list x 2))))
(list 5 50 9000))
</syntaxhighlight>
</lang>
{{out|note=for both examples}}
<pre>
Line 3,035:
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang=lb>for a = 0 to 16
print a;"=";dec2bin$(a)
next
Line 3,050:
wend
end function
</syntaxhighlight>
</lang>
 
=={{header|Little Man Computer}}==
Line 3,056:
 
The maximum integer in LMC is 999, so 90000 in the task is here replaced by 900.
<langsyntaxhighlight lang=Little Man Computer>
// Little Man Computer, for Rosetta Code.
// Read numbers from user and display them in binary.
Line 3,116:
nrDigits DAT
diff DAT
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,127:
=={{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 3,306:
!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 3,330:
 
=={{header|Locomotive Basic}}==
<langsyntaxhighlight lang=locobasic>10 PRINT BIN$(5)
20 PRINT BIN$(50)
30 PRINT BIN$(9000)</langsyntaxhighlight>
{{out}}
<pre>101
Line 3,339:
 
=={{header|LOLCODE}}==
<langsyntaxhighlight lang=LOLCODE>HAI 1.3
HOW IZ I DECIMULBINUR YR DECIMUL
I HAS A BINUR ITZ ""
Line 3,354:
VISIBLE I IZ DECIMULBINUR YR 50 MKAY
VISIBLE I IZ DECIMULBINUR YR 9000 MKAY
KTHXBYE</langsyntaxhighlight>
 
{{out}}
Line 3,363:
=={{header|Lua}}==
===Lua - Iterative===
<langsyntaxhighlight lang=Lua>function dec2bin (n)
local bin = ""
while n > 0 do
Line 3,374:
print(dec2bin(5))
print(dec2bin(50))
print(dec2bin(9000))</langsyntaxhighlight>
{{out}}
<pre>101
Line 3,381:
===Lua - Recursive===
{{works with|Lua|5.3+}}
<langsyntaxhighlight lang=lua>function dec2bin(n, bin)
bin = (n&1) .. (bin or "") -- use n%2 instead of n&1 for Lua 5.1/5.2
return n>1 and dec2bin(n//2, bin) or bin -- use math.floor(n/2) instead of n//2 for Lua 5.1/5.2
Line 3,388:
print(dec2bin(5))
print(dec2bin(50))
print(dec2bin(9000))</langsyntaxhighlight>
{{out}}
<pre>101
Line 3,395:
 
=={{header|M2000 Interpreter}}==
<langsyntaxhighlight lang=M2000 Interpreter>
Module Checkit {
Form 90, 40
Line 3,449:
}
Checkit
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 3,469:
matches the binary representation of the input, e.g. <code>BINARY.(5)</code> is <code>101</code>.
 
<langsyntaxhighlight lang=MAD> NORMAL MODE IS INTEGER
INTERNAL FUNCTION(NUM)
Line 3,489:
 
VECTOR VALUES FMT = $I4,2H: ,I16*$
END OF PROGRAM </langsyntaxhighlight>
{{out}}
<pre> 5: 101
Line 3,496:
 
=={{header|Maple}}==
<langsyntaxhighlight lang=Maple>
> convert( 50, 'binary' );
110010
> convert( 9000, 'binary' );
10001100101000
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight lang=Mathematica>StringJoin @@ ToString /@ IntegerDigits[50, 2] </langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight lang=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}}==
<langsyntaxhighlight lang=maxima>digits([arg]) := block(
[n: first(arg), b: if length(arg) > 1 then second(arg) else 10, v: [ ], q],
do (
Line 3,524:
/*
10001100101000
*/</langsyntaxhighlight>
 
=={{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 3,550:
print binString
)
</syntaxhighlight>
</lang>
{{out}}
Output to MAXScript Listener:
Line 3,574:
 
=={{header|Mercury}}==
<langsyntaxhighlight lang=mercury>:- module binary_digits.
:- interface.
 
Line 3,590:
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.19.3}}
<langsyntaxhighlight lang=min>(2 over over mod 'div dip) :divmod2
 
(
Line 3,603:
) :bin
 
(5 50 9000) (bin puts) foreach</langsyntaxhighlight>
{{out}}
<pre>
Line 3,613:
=={{header|MiniScript}}==
=== Iterative ===
<langsyntaxhighlight lang=MiniScript>binary = function(n)
result = ""
while n
Line 3,626:
print binary(50)
print binary(9000)
print binary(0)</langsyntaxhighlight>
 
=== Recursive ===
<langsyntaxhighlight lang=MiniScript>binary = function(n,result="")
if n == 0 then
if result == "" then return "0" else return result
Line 3,640:
print binary(50)
print binary(9000)
print binary(0)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,650:
 
=={{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 3,667:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang=modula2>MODULE Binary;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT Write,WriteLn,ReadChar;
Line 3,695:
 
ReadChar
END Binary.</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang=modula3>MODULE Binary EXPORTS Main;
 
IMPORT IO, Fmt;
Line 3,708:
num := 150;
IO.Put(Fmt.Int(num, 2) & "\n");
END Binary.</langsyntaxhighlight>
{{out}}
<pre>
Line 3,716:
 
=={{header|NetRexx}}==
<langsyntaxhighlight lang=NetRexx>/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 3,733:
w_ = list.word(n_)
say w_.right(20)':' getBinaryDigits(w_)
end n_</langsyntaxhighlight>
{{out}}
<pre>
Line 3,744:
=={{header|NewLisp}}==
 
<langsyntaxhighlight lang=NewLisp>
;;; Using the built-in "bits" function
;;; For integers up to 9,223,372,036,854,775,807
Line 3,757:
;;; Example
(println (big-bits 1234567890123456789012345678901234567890L))
</syntaxhighlight>
</lang>
<pre>
Output:
Line 3,781:
 
=={{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 3,804:
 
for i in 0..15:
echo toBin(i)</langsyntaxhighlight>
{{out}}
<pre>0
Line 3,824:
 
===Version using strformat===
<langsyntaxhighlight lang=Nim>import strformat
 
for n in 0..15:
echo fmt"{n:b}"</langsyntaxhighlight>
 
{{out}}
Line 3,848:
 
=={{header|Oberon-2}}==
<langsyntaxhighlight lang=oberon2>
MODULE BinaryDigits;
IMPORT Out;
Line 3,866:
OutBin(42); Out.Ln;
END BinaryDigits.
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,878:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang=objeck>class Binary {
function : Main(args : String[]) ~ Nil {
5->ToBinaryString()->PrintLine();
Line 3,884:
9000->ToBinaryString()->PrintLine();
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,893:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang=ocaml>let bin_of_int d =
if d < 0 then invalid_arg "bin_of_int" else
if d = 0 then "0" else
Line 3,904:
let () =
let d = read_int () in
Printf.printf "%8s\n" (bin_of_int d)</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 3,925:
 
=={{header|Ol}}==
<langsyntaxhighlight lang=scheme>
(print (number->string 5 2))
(print (number->string 50 2))
(print (number->string 9000 2))
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,939:
=={{header|OxygenBasic}}==
The Assembly code uses block structures to minimise the use of labels.
<langsyntaxhighlight lang=oxygenbasic>
 
function BinaryBits(sys n) as string
Line 3,983:
 
print BinaryBits 0xaa 'result 10101010
</syntaxhighlight>
</lang>
 
=={{header|Panda}}==
<syntaxhighlight lang =panda>0..15.radix:2 nl</langsyntaxhighlight>
{{out}}
<pre>0
Line 4,006:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang=parigp>bin(n:int)=concat(apply(s->Str(s),binary(n)))</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free Pascal}}
FPC compiler Version 2.6 upwards.The obvious version.
<langsyntaxhighlight lang=pascal>program IntToBinTest;
{$MODE objFPC}
uses
Line 4,039:
IntBinTest(5);IntBinTest(50);IntBinTest(5000);
IntBinTest(0);IntBinTest(NativeUint(-1));
end.</langsyntaxhighlight>
{{out}}
<pre> 5 101
Line 4,051:
Beware of the endianess of the constant.
I check performance with random Data.
<langsyntaxhighlight lang=pascal>
program IntToPcharTest;
uses
Line 4,157:
Writeln(cnt/rounds+1:6:3);
FreeMem(s);
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 4,173:
 
=={{header|Peloton}}==
<langsyntaxhighlight lang=sgml><@ defbaslit>2</@>
 
<@ saybaslit>0</@>
Line 4,179:
<@ saybaslit>50</@>
<@ saybaslit>9000</@>
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
<langsyntaxhighlight lang=perl>for (5, 50, 9000) {
printf "%b\n", $_;
}</langsyntaxhighlight>
<pre>
101
Line 4,192:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%b\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%b\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">50</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%b\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9000</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 4,205:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight lang=Phixmonti>def printBinary
"The decimal value " print dup print " should produce an output of " print
20 int>bit
Line 4,227:
5 printBinary
50 printBinary
9000 printBinary</langsyntaxhighlight>
 
Other solution
<langsyntaxhighlight lang=Phixmonti>/# Rosetta Code problem: http://rosettacode.org/wiki/Binary_digits
by Galileo, 05/2022 #/
 
Line 4,248:
50 printBinary
9000 printBinary
</syntaxhighlight>
</lang>
{{out}}
<pre>The decimal value 5 should produce an output of 101
Line 4,257:
 
=={{header|PHP}}==
<langsyntaxhighlight lang=php><?php
echo decbin(5);
echo decbin(50);
echo decbin(9000);</langsyntaxhighlight>
{{out}}
<pre>101
Line 4,267:
 
=={{header|Picat}}==
<langsyntaxhighlight lang=Picat> foreach(I in [5,50,900])
println(to_binary_string(I))
end.</langsyntaxhighlight>
 
{{out}}
Line 4,278:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight lang=PicoLisp>: (bin 5)
-> "101"
 
Line 4,285:
 
: (bin 9000)
-> "10001100101000"</langsyntaxhighlight>
 
=={{header|Piet}}==
Line 4,447:
=={{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 4,458:
 
put string(text) edit (2147483647) (b);
put skip list (trim(text, '0'));</langsyntaxhighlight>
{{out}}
<pre>
Line 4,466:
 
=={{header|PL/M}}==
<langsyntaxhighlight lang=plm>100H:
 
/* CP/M BDOS CALL */
Line 4,501:
 
CALL BDOS(0,0);
EOF</langsyntaxhighlight>
{{out}}
<pre>101
Line 4,509:
=={{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 4,521:
PRINT STR$(d(i)) & ": " & BIN$(d(i)) & " (" & BIN$(d(i), 32) & ")"
NEXT i
END FUNCTION</langsyntaxhighlight>
{{out}}<pre>
5: 101 (00000000000000000000000000000101)
Line 4,530:
=={{header|PowerShell}}==
{{libheader|Microsoft .NET Framework}}
<langsyntaxhighlight lang=PowerShell>@(5,50,900) | foreach-object { [Convert]::ToString($_,2) }</langsyntaxhighlight>
{{out}}
<pre>101
Line 4,537:
 
=={{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
Line 4,558:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang=PureBasic>If OpenConsole()
PrintN(Bin(5)) ;101
PrintN(Bin(50)) ;110010
Line 4,565:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>101
Line 4,574:
===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 4,591:
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 4,612:
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 4,633:
1101
1110
1111</langsyntaxhighlight>
 
===Custom functions===
 
Defined in terms of a more general '''showIntAtBase''' function:
<langsyntaxhighlight lang=python>'''Binary strings for integers'''
 
 
Line 4,727:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Mapping showBinary over integer list:
Line 4,741:
 
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 4,861:
# MAIN -------------------------------------------------
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Mapping a composed function:
Line 4,874:
 
=={{header|QB64}}==
<langsyntaxhighlight lang=QB64>
Print DecToBin$(5)
Print DecToBin$(50)
Line 4,925:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
Quackery provides built-in radix control, much like Forth.
<langsyntaxhighlight lang=quackery>
2 base put ( Numbers will be output in base 2 now. )
( Bases from 2 to 36 (inclusive) are supported. )
Line 4,939:
base release ( It's best to clean up after ourselves. )
( Numbers will be output in base 10 now. )
</syntaxhighlight>
</lang>
 
A user-defined conversion might look something like this:
<langsyntaxhighlight lang=quackery>
[ [] swap
[ 2 /mod digit
Line 4,953:
50 bin echo$ cr
9000 bin echo$ cr
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,962:
 
=={{header|R}}==
<langsyntaxhighlight lang=rsplus>
dec2bin <- function(num) {
ifelse(num == 0,
Line 4,973:
cat(dec2bin(anumber),"\n")
}
</syntaxhighlight>
</lang>
'''output'''
<pre>
Line 4,983:
 
=={{header|Racket}}==
<langsyntaxhighlight lang=racket>
#lang racket
;; Option 1: binary formatter
Line 4,989:
;; 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 perl6line>say .fmt("%b") for 5, 50, 9000;</langsyntaxhighlight>
<pre>
101
Line 5,003:
Alternatively:
 
<syntaxhighlight lang=raku perl6line>say .base(2) for 5, 50, 9000;</langsyntaxhighlight>
<pre>101
110010
Line 5,009:
 
=={{header|RapidQ}}==
<syntaxhighlight lang=vb>
<lang vb>
'Convert Integer to binary string
Print "bin 5 = ", bin$(5)
Line 5,015:
Print "bin 9000 = ",bin$(9000)
sleep 10
</syntaxhighlight>
</lang>
 
=={{header|Red}}==
<langsyntaxhighlight lang=Red>Red []
 
foreach number [5 50 9000] [
Line 5,025:
print reduce [ pad/left number 5 binstr ]
]
</syntaxhighlight>
</lang>
'''output'''
<pre> 5 101
Line 5,033:
 
=={{header|Retro}}==
<langsyntaxhighlight lang=Retro>9000 50 5 3 [ binary putn cr decimal ] times</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 5,040:
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 lang=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,050:
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 5,062:
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 lang=REXX>/*REXX program to convert several decimal numbers to binary (or base 2). */
@.=; @.1= 0
@.2= 5
Line 5,072:
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 lang=REXX>/*REXX program to convert several decimal numbers to binary (or base 2). */
@.=; @.1= 0
@.2= 5
Line 5,086:
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 lang=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,104:
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 5,116:
 
=={{header|Ring}}==
<langsyntaxhighlight lang=ring>
see "Number to convert : "
give a
Line 5,129:
else see 0 ok
next
</syntaxhighlight>
</lang>
 
=={{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 5,145:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang=runbasic>input "Number to convert:";a
while 2^(n+1) < a
n = n + 1
Line 5,158:
print 0;
end if
next</langsyntaxhighlight>
{{out}}
<pre>Number to convert:?9000
Line 5,164:
 
=={{header|Rust}}==
<langsyntaxhighlight lang=rust>fn main() {
for i in 0..8 {
println!("{:b}", i)
}
}</langsyntaxhighlight>
Outputs:
<pre>0
Line 5,180:
 
=={{header|S-lang}}==
<langsyntaxhighlight lang=S-lang>define int_to_bin(d)
{
variable m = 0x40000000, prn = 0, bs = "";
Line 5,200:
() = 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
Line 5,208:
=={{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 5,215:
 
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|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 5,234:
writeln(number radix 2);
end for;
end func;</langsyntaxhighlight>
{{out}}
<pre>
Line 5,257:
 
=={{header|SequenceL}}==
<langsyntaxhighlight lang=sequencel>main := toBinaryString([5, 50, 9000]);
 
toBinaryString(number(0)) :=
Line 5,265:
toBinaryString(floor(number/2)) ++ val when floor(number/2) > 0
else
val;</langsyntaxhighlight>
 
{{out}}
Line 5,273:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang=ruby>[5, 50, 9000].each { |n|
say n.as_bin;
}</langsyntaxhighlight>
{{out}}
<pre>101
Line 5,282:
 
=={{header|Simula}}==
<langsyntaxhighlight lang=simula>BEGIN
 
PROCEDURE OUTINTBIN(N); INTEGER N;
Line 5,296:
END;
 
END</langsyntaxhighlight>
{{out}}
<pre>
Line 5,306:
=={{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
Line 5,317:
 
=={{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}}==
<langsyntaxhighlight lang=snobol4>
define('bin(n,r)') :(bin_end)
bin bin = le(n,0) r :s(return)
Line 5,333:
output = bin(50)
output = bin(9000)
end</langsyntaxhighlight>
{{out}}
<pre>
Line 5,342:
 
=={{header|SNUSP}}==
<langsyntaxhighlight lang=SNUSP>
/recurse\
$,binary!\@\>?!\@/<@\.#
Line 5,348:
/<+>- \ 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 lang=Swift>for num in [5, 50, 9000] {
println(String(num, radix: 2))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,366:
 
=={{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 5,379:
puts [num2bin 5]
puts [num2bin 50]
puts [num2bin 9000]</langsyntaxhighlight>
{{out}}
<pre>
Line 5,405:
<br>
Or you can use the builtin format:
<langsyntaxhighlight lang=tcl>foreach n {0 1 5 50 9000} {
puts [format "%4u: %b" $n $n]
}</langsyntaxhighlight>
{{out}}
<pre> 0: 0
Line 5,417:
=={{header|TI-83 BASIC}}==
Using Standard TI-83 BASIC
<langsyntaxhighlight lang=ti83b>PROGRAM:BINARY
:Disp "NUMBER TO"
:Disp "CONVERT:"
Line 5,435:
:N-1→N
:End
:Disp B</langsyntaxhighlight>
Alternate using a string to display larger numbers.
<langsyntaxhighlight lang=ti83b>PROGRAM:BINARY
:Input X
:" "→Str1
Line 5,445:
: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 5,466:
: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 5,502:
130 Print "D"; : Return
140 Print "E"; : Return
150 Print "F"; : Return</langsyntaxhighlight>
{{out}}
<pre>Enter base (1<X<17): 2
Line 5,511:
 
=={{header|UNIX Shell}}==
<langsyntaxhighlight lang=sh># Define a function to output binary digits
tobinary() {
# We use the bench calculator for our conversion
Line 5,519:
# Call the function with each of our values
tobinary 5
tobinary 50</langsyntaxhighlight>
 
=={{header|VBA}}==
Line 5,541:
Places is useful for padding the return value with leading 0s (zeros).
 
<syntaxhighlight lang=vb>
<lang vb>
Option Explicit
 
Line 5,580:
End If
End Function
</syntaxhighlight>
</lang>
{{out}}
<pre>The decimal value 5 should produce an output of : 101
Line 5,591:
=={{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 5,607:
EOL
Ins_Newline
Return </langsyntaxhighlight>
Example output when values 0, 1, 5, 50 and 9000 were entered:
<pre>
Line 5,618:
 
=={{header|Vim Script}}==
<langsyntaxhighlight lang=vim>function Num2Bin(n)
let n = a:n
let s = ""
Line 5,638:
echo Num2Bin(5)
echo Num2Bin(50)
echo Num2Bin(9000)</langsyntaxhighlight>
 
{{Out}}
Line 5,647:
=={{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 5,682:
Debug.Print Bin(9000)
End Sub
</syntaxhighlight>
</lang>
{{out}}
<pre>101
Line 5,689:
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang=vbnet>Module Program
Sub Main
For Each number In {5, 50, 9000}
Line 5,695:
Next
End Sub
End Module</langsyntaxhighlight>
{{out}}
<pre>101
Line 5,702:
 
=={{header|Visual FoxPro}}==
<langsyntaxhighlight lang=vfp>
*!* Binary Digits
CLEAR
Line 5,728:
RETURN FLOOR(v)
ENDFUNC
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,740:
This program prints binary numbers until the internal representation of the current integer overflows to -1; it will never do so on some interpreters. It is almost an exact duplicate of [[Count in octal#Whitespace]].
 
<langsyntaxhighlight lang=Whitespace>
 
Line 5,779:
 
 
</langsyntaxhighlight>
 
It was generated from the following pseudo-Assembly.
 
<langsyntaxhighlight lang=asm>push 0
; Increment indefinitely.
0:
Line 5,815:
3:
pop
ret</langsyntaxhighlight>
 
=={{header|Vlang}}==
<langsyntaxhighlight lang=vlang>fn main() {
for i in 0..16 {
println("${i:b}")
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,844:
 
=={{header|VTL-2}}==
<langsyntaxhighlight lang=VTL2>10 N=5
20 #=100
30 N=50
Line 5,859:
180 #=I<18*160
190 ?=""
200 #=;</langsyntaxhighlight>
{{out}}
<pre>101
Line 5,867:
=={{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
Line 5,879:
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang=ecmascript>import "/fmt" for Fmt
System.print("Converting to binary:")
for (i in [5, 50, 9000]) Fmt.print("$d -> $b", i, i)</langsyntaxhighlight>
 
{{out}}
Line 5,894:
=={{header|X86 Assembly}}==
Translation of XPL0. Assemble with tasm, tlink /t
<langsyntaxhighlight lang=asm> .model tiny
.code
.486
Line 5,922:
int 29h ;display character
ret
end start</langsyntaxhighlight>
 
{{out}}
Line 5,932:
 
=={{header|XPL0}}==
<langsyntaxhighlight lang=XPL0>include c:\cxpl\codes; \intrinsic code declarations
 
proc BinOut(N); \Output N in binary
Line 5,948:
I:= I+1;
until KeyHit or I=0;
]</langsyntaxhighlight>
 
{{out}}
Line 5,969:
 
=={{header|Yabasic}}==
<langsyntaxhighlight lang=yabasic>dim a(3)
a(0) = 5
a(1) = 50
Line 5,977:
print a(i) using "####", " -> ", bin$(a(i))
next i
end</langsyntaxhighlight>
 
=={{header|Z80 Assembly}}==
{{trans|8086 Assembly}}
 
<langsyntaxhighlight lang=z80>org &8000
PrintChar equ &BB5A ;syscall - prints accumulator to Amstrad CPC's screen
 
Line 6,054:
call &BB5A
ld a,10
jp &BB5A ;its ret will return for us.</langsyntaxhighlight>
 
 
This is another version. Output of the result over port 0A hex.
<langsyntaxhighlight lang=z80>
; HL contains the value to be converted
ld hl,5
Line 6,104:
djnz bitloop
 
ret</langsyntaxhighlight>
 
 
=={{header|zkl}}==
<syntaxhighlight lang =zkl>(9000).toString(2)</langsyntaxhighlight>
<langsyntaxhighlight lang=zkl>T(5,50,9000).apply("toString",2) //--> L("101","110010","10001100101000")</langsyntaxhighlight>
<syntaxhighlight lang =zkl>"%.2B".fmt(9000)</langsyntaxhighlight>
 
=={{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 6,127:
1070 IF (sf <> 0) THEN LET s$=s$+d$
1080 NEXT l
1090 RETURN</langsyntaxhighlight>
10,327

edits