Binary digits: Difference between revisions
Add Refal
(→{{header|Commodore BASIC}}: Add output) |
Not a robot (talk | contribs) (Add Refal) |
||
(48 intermediate revisions by 20 users not shown) | |||
Line 1:
[[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">
2 base drop
#50 . cr
</syntaxhighlight>
{{out}}
<pre>
110010
</pre>
=={{header|11l}}==
<
print(‘#4 = #.’.format(n, bin(n)))</
{{out}}
<pre>
Line 49 ⟶ 34:
9000 = 10001100101000
</pre>
=={{header|360 Assembly}}==
<
BINARY CSECT
USING BINARY,R12
Line 93 ⟶ 77:
CBIN DC CL32' ' binary value
YREGS
END BINARY</
{{out}}
<pre>
Line 101 ⟶ 85:
9000 10001100101000
</pre>
=={{header|0815}}==
<syntaxhighlight lang="0815">}:r:|~ Read numbers in a loop.
}:b: Treat the queue as a stack and
<:2:= accumulate the binary digits
/=>&~ of the given number.
^:b:
<:0:-> Enqueue negative 1 as a sentinel.
{ Dequeue the first binary digit.
}:p:
~%={+ Rotate each binary digit into place and print it.
^:p:
<:a:~$ Output a newline.
^:r:</syntaxhighlight>
{{out}}
Note that 0815 reads numeric input in hexadecimal.
<syntaxhighlight lang="bash">echo -e "5\n32\n2329" | 0815 bin.0
101
110010
10001100101001</syntaxhighlight>
=={{header|6502 Assembly}}==
{{works with|http://vice-emu.sourceforge.net/ VICE}}
Line 122 ⟶ 127:
strout = $cb1e
</pre>
<
; C64 - Binary digits
; http://rosettacode.org/wiki/Binary_digits
Line 213 ⟶ 218:
binstr .repeat 16, $00 ; reserve 16 bytes for the binary digits
.byte $0d, $00 ; newline + null terminator
</syntaxhighlight>
{{out}}
<pre>
Line 228 ⟶ 233:
100
</pre>
=={{header|8080 Assembly}}==
<
puts: equ 9h ; Print string
org 100h
Line 261 ⟶ 265:
jmp binlp ; Otherwise, do next bit
binstr: db '0000000000000000' ; Placeholder for string
binend: db 13,10,'$' ; end with \r\n </
{{out}}
Line 270 ⟶ 274:
</pre>
=={{header|8086 Assembly}}==
<
.stack 1024
.data
Line 356 ⟶ 359:
pop ax
ret
PrintBinary_NoLeadingZeroes endp</
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program binarydigit.s */
Line 524 ⟶ 516:
.include "../includeARM64.inc"
</syntaxhighlight>
{{out}}
<pre>
Line 532 ⟶ 524:
The decimal value +1 should produce an output of 1
</pre>
=={{header|ACL2}}==
<
(defun bin-string-r (x)
Line 548 ⟶ 539:
(if (zp x)
"0"
(bin-string-r x)))</
=={{header|Action!}}==
<
CHAR ARRAY a(16)
BYTE i=[0]
Line 581 ⟶ 571:
PutE()
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Binary_digits.png Screenshot from Atari 8-bit computer]
Line 590 ⟶ 580:
Output for 9000 is 10001100101000
</pre>
=={{header|Ada}}==
<
procedure binary is
bit : array (0..1) of character := ('0','1');
Line 605 ⟶ 594:
put_line ("Output for" & test'img & " is " & bin_image (test));
end loop;
end binary;</
{{out}}
Line 613 ⟶ 602:
Output for 9000 is 10001100101000
</pre>
=={{header|Aime}}==
<
o_byte('\n');
o_xinteger(2, 5);
Line 621 ⟶ 609:
o_xinteger(2, 50);
o_byte('\n');
o_form("/x2/\n", 9000);</
{{out}}
<pre>0
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'''<
printf((
Line 645 ⟶ 632:
50, " => ", []BOOL(BIN 50)[bits width-6+1:], new line,
9000, " => ", []BOOL(BIN 9000)[bits width-14+1:], new line
))</
{{out}}
<pre>
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}}==
<
procedure writebin(n);
integer n;
Line 674 ⟶ 685:
writebin(50);
writebin(9000);
end</
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|APL}}==
Works in: [[Dyalog APL]]
A builtin function. Produces a boolean array.
<syntaxhighlight lang
Line 690 ⟶ 700:
Produces a boolean array.
<
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|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)
<
-- showBin :: Int -> String
Line 833 ⟶ 816:
on unlines(xs)
intercalate(linefeed, xs)
end unlines</
<pre>5 -> 101
50 -> 110010
Line 839 ⟶ 822:
Or using:
<
on showBin(n)
script binaryChar
Line 847 ⟶ 830:
end script
showIntAtBase(2, binaryChar, n, "")
end showBin</
{{Out}}
<pre>5 -> 一〇一
Line 857 ⟶ 840:
At its very simplest, an AppleScript solution would look something like this:
<
set binary to (n mod 2 div 1) as text
set n to n div 2
Line 871 ⟶ 854:
intToBinary(5) & linefeed & ¬
intToBinary(50) & linefeed & ¬
intToBinary(9000) & linefeed</
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:
<
set binary to ""
repeat
Line 897 ⟶ 880:
intToBinary(5) & linefeed & ¬
intToBinary(50) & linefeed & ¬
intToBinary(9000) & linefeed</
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 1,065 ⟶ 1,047:
.Ls_magic_number_10: .word 0x66666667
</syntaxhighlight>
=={{header|Arturo}}==
<
print as.binary 50
print as.binary 9000</
{{out}}
Line 1,077 ⟶ 1,058:
110010
10001100101000</pre>
=={{header|AutoHotkey}}==
<
MsgBox % NumberToBinary(50) ;110010
MsgBox % NumberToBinary(9000) ;10001100101000
Line 1,088 ⟶ 1,068:
Result := (InputNumber & 1) . Result, InputNumber >>= 1
Return, Result
}</
=={{header|AutoIt}}==
<
ConsoleWrite(IntToBin(50) & @CRLF)
Line 1,107 ⟶ 1,086:
Return $r
EndFunc ;==>IntToBin
</syntaxhighlight>
=={{header|AWK}}==
<
print tobinary(0)
print tobinary(1)
print tobinary(5)
print tobinary(50)
Line 1,117 ⟶ 1,098:
function tobinary(num) {
outstr =
return outstr
}</
=={{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.
<
.Axe supports 16-bit integers, so 16 digits are enough
L₁+16→P
Line 1,146 ⟶ 1,116:
End
Disp P,i
Return</
=={{header|BaCon}}==
<
OPTION MEMTYPE int
INPUT n$
Line 1,156 ⟶ 1,125:
ELSE
PRINT CHOP$(BIN$(VAL(n$)), "0", 1)
ENDIF</
=={{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}}===
<
1 LET N2 = ABS ( INT (N))
2 LET B$ = ""
Line 1,170:
7 NEXT N1
8 PRINT B$
9 RETURN</
{{out}}
<pre>101
Line 1,178:
==={{header|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>
{{out}}
<pre>
Line 1,198:
==={{header|BBC BASIC}}===
<
PRINT FN_tobase(num%, 2, 0)
NEXT
Line 1,213:
M% -= 1
UNTIL (N%=FALSE OR N%=TRUE) AND M%<=0
=A$</
The above is a generic "Convert to any base" program.
Here is a faster "Convert to Binary" program:
<
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$</
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">10 for c = 1 to 3
20 read n
30 print n;"-> ";vin$(n)
40 next c
80 end
100 sub vin$(n)
110 b$ = ""
120 n = abs(int(n))
130 '
140 b$ = str$(n mod 2)+b$
150 n = int(n/2)
160 if n > 0 then 130
170 vin$ = b$
180 end sub
200 data 5,50,9000</syntaxhighlight>
==={{header|Commodore BASIC}}===
Since the task only requires nonnegative integers, we use a negative one to signal the end of the demonstration data.
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
40 PRINT N"-> "B$
50 GOTO 10
60 DATA 5, 50, 9000, -1
70 END
90 REM *** SUBROUTINE: CONVERT INTEGER IN N TO BINARY STRING B$
100 B$=""
110 FOR N1 = ABS(INT(N)) TO 0 STEP 0
120 : B$ = MID$(STR$(N1 AND 1),2) + B$
130 : N1 = INT(N1/2)
140 NEXT N1
150 RETURN</syntaxhighlight>
{{Out}}
<pre>
9000 -> 10001100101000
</pre>
==={{header|IS-BASIC}}===
<
100 DEF BIN$(N)
110 LET N=ABS(INT(N)):LET B$=""
Line 1,260 ⟶ 1,282:
150 LOOP WHILE N>0
160 LET BIN$=B$
170 END DEF</
==={{header|QBasic}}===
<
N = ABS(INT(N))
B$ = ""
Line 1,276 ⟶ 1,298:
PRINT USING fmt$; 5; BIN$(5)
PRINT USING fmt$; 50; BIN$(50)
PRINT USING fmt$; 9000; BIN$(9000)</
==={{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.
<
REM A-O: binary digits with A least significant and N most significant
REM X: number whose binary expansion we want
Line 1,364 ⟶ 1,386:
999 PRINT 0 REM zero is the one time we DO want to print a leading zero
END</
==={{header|True BASIC}}===
<
LET N = ABS(INT(N))
LET B$ = ""
Line 1,385 ⟶ 1,407:
PRINT USING "####": 9000;
PRINT " -> "; BIN$(9000)
END</
==={{header|
{{works with|Windows XBasic}}
<syntaxhighlight lang="qbasic">PROGRAM "binardig"
VERSION "0.0000"
DECLARE FUNCTION Entry ()
FUNCTION Entry ()
DIM a[3]
a[0] = 5
a[1] = 50
a[2] = 9000
FOR i = 0 TO 2
PRINT FORMAT$ ("####", a[i]); " -> "; BIN$(a[i])
NEXT i
END FUNCTION
END PROGRAM</syntaxhighlight>
=={{header|Batch File}}==
This num2bin.bat file handles non-negative input as per the requirements with no leading zeros in the output. Batch only supports signed integers. This script also handles negative values by printing the appropriate two's complement notation.
<
:num2bin IntVal [RtnVar]
setlocal enableDelayedExpansion
Line 1,435 ⟶ 1,444:
if "%~2" neq "" (set %~2=%rtn%) else echo %rtn%
)
exit /b</
=={{header|bc}}==
{{trans|dc}}
<
5
50
9000
quit</
=={{header|BCPL}}==
<
let writebin(x) be
Line 1,461 ⟶ 1,468:
writebin(50)
writebin(9000)
$)</
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|Beads}}==
<
calc main_init
loop across:[5, 50, 9000] val:v
log to_str(v, base:2)</
{{out}}
<pre>101
Line 1,477 ⟶ 1,483:
10001100101000
</pre>
=={{header|Befunge}}==
Reads the number to convert from standard input.
<
{{out}}
<pre>9000
10001100101000</pre>
=={{header|BQN}}==
A BQNcrate idiom which returns the digits as a boolean array.
<
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}}==
<
= bit bits
. :?bits
Line 1,509 ⟶ 1,512:
& put$(str$(!dec ":\n" dec2bin$!dec \n\n))
)
;</
{{out}}
<pre>0:
Line 1,525 ⟶ 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.
<
[>>++<< Set up {n 0 2} for divmod magic
[->+>- Then
Line 1,546 ⟶ 1,548:
<[[-]<] Zero the tape for the next iteration
++++++++++. Print a newline
[-]<+] Zero it then increment n and go again</
=={{header|Burlesque}}==
<
blsq ) {5 50 9000}{2B!}m[uN
101
110010
10001100101000
</syntaxhighlight>
=={{header|C}}==
===With bit level operations===
<
#define _CRT_NONSTDC_NO_DEPRECATE // enable old-gold POSIX names in MSVS
Line 1,664:
return EXIT_SUCCESS;
}
</syntaxhighlight>
{{output}}
<pre>itoa: 5 decimal = 101 binary
Line 1,678:
===With malloc and log10===
Converts int to a string.
<
#include <stdio.h>
#include <stdlib.h>
Line 1,704:
ret[bits] = '\0';
return ret;
}</
{{out}}
Line 1,727:
10010
10011</pre>
=={{header|C sharp|C#}}==
<
class Program
Line 1,740 ⟶ 1,739:
}
}
}</
Another version using dotnet 5<
using System.Text;
Line 1,754 ⟶ 1,753:
Console.WriteLine(ToBinary(5));
Console.WriteLine(ToBinary(50));
Console.WriteLine(ToBinary(9000));</
{{out}}
<pre>
Line 1,761 ⟶ 1,760:
10001100101000
</pre>
=={{header|C++}}==
<
#include <iostream>
#include <limits>
Line 1,785 ⟶ 1,783:
print_bin(9000);
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,794 ⟶ 1,792:
</pre>
Shorter version using bitset
<
#include <bitset>
void printBits(int n) { // Use int like most programming languages.
Line 1,807 ⟶ 1,805:
printBits(50);
printBits(9000);
} // for testing with n=0 printBits<32>(0);</
Using >> operator. (1st example is 2.75x longer. Matter of taste.)
<
int main(int argc, char* argv[]) {
unsigned int in[] = {5, 50, 9000}; // Use int like most programming languages
Line 1,817 ⟶ 1,815:
std::cout << ('0' + b & 1) << (!at ? "\n": ""); // '0' or '1'. Add EOL if last bit of num
}
</syntaxhighlight>
To be fair comparison with languages that doesn't declare a function like C++ main(). 3.14x shorter than 1st example.
<
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,826 ⟶ 1,824:
std::cout << ('0' + b & 1) << (!at ? "\n": ""); // '0' or '1'. Add EOL if last bit of num
}
</syntaxhighlight>
Using bitwise operations with recursion.
<
#include <iostream>
Line 1,840 ⟶ 1,838:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,847 ⟶ 1,845:
10001100101000
</pre>
=={{header|Ceylon}}==
<
void printBinary(Integer integer) =>
Line 1,857 ⟶ 1,854:
printBinary(50);
printBinary(9k);
}</
=={{header|Clojure}}==
<
(Integer/toBinaryString 50)
(Integer/toBinaryString 9000)</
=={{header|CLU}}==
<
bin: string := ""
while n > 0 do
Line 1,881 ⟶ 1,876:
stream$putl(po, int$unparse(test) || " -> " || binary(test))
end
end start_up</
{{out}}
<pre>5 -> 101
50 -> 110010
9000 -> 10001100101000</pre>
=={{header|COBOL}}==
<
PROGRAM-ID. SAMPLE.
Line 1,914 ⟶ 1,908:
display binary_number
stop run.
</syntaxhighlight>
Free-form, using a reference modifier to index into binary-number.
<
PROGRAM-ID. binary-conversion.
Line 1,942 ⟶ 1,936:
end-perform.
display binary-number.
stop run.</
=={{header|CoffeeScript}}==
<
new Number(n).toString(2)
console.log binary n for n in [5, 50, 9000]</
=={{header|Common Lisp}}==
Just print the number with "~b":
<
; or
(write 5 :base 2)</
=={{header|Component Pascal}}==
BlackBox Component Builder
<
MODULE BinaryDigits;
IMPORT StdLog,Strings;
Line 1,976 ⟶ 1,967:
END Do;
END BinaryDigits.
</syntaxhighlight>
Execute: ^Q BinaryDigits.Do <br/>
{{out}}
Line 1,983 ⟶ 1,974:
50:> 110010
9000:> 10001100101000</pre>
=={{header|Cowgol}}==
<
sub print_binary(n: uint32) is
Line 2,004 ⟶ 1,994:
print_binary(5);
print_binary(50);
print_binary(9000);</
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|Crystal}}==
{{trans|Ruby}}
Using an array
<
puts "%b" % n
end</
Using a tuple
<
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|D}}==
<
import std.stdio;
foreach (immutable i; 0 .. 16)
writefln("%b", i);
}</
{{out}}
<pre>0
Line 2,047 ⟶ 2,035:
1110
1111</pre>
=={{header|Dart}}==
<
if(n<0)
throw new IllegalArgumentException("negative numbers require 2s complement");
Line 2,073 ⟶ 2,060:
// fails due to precision limit
print(binary(0x123456789abcdef));
}</
=={{header|dc}}==
<syntaxhighlight lang
{{out}}
Line 2,082 ⟶ 2,068:
110010
10001100101000</pre>
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
program BinaryDigit;
{$APPTYPE CONSOLE}
Line 2,103 ⟶ 2,088:
writeln(' 50: ',IntToBinStr(50));
writeln('9000: '+IntToBinStr(9000));
end.</
{{out}}
<pre>
Line 2,110 ⟶ 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
<
var s = ""
for x in 31^-1..0 {
Line 2,127 ⟶ 2,132:
}
print("5 == \(5), 50 = \(50), 1000 = \(9000)")</
{{out}}
<pre>5 == 101, 50 = 110010, 1000 = 10001100101000</pre>
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
while
return num &
.
</syntaxhighlight>
{{out}}
<pre>
101
Line 2,166 ⟶ 2,158:
=={{header|EchoLisp}}==
<
;; primitive : (number->string number [base]) - default base = 10
Line 2,176 ⟶ 2,168:
110010
10001100101000
</syntaxhighlight>
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module BinaryDigits {
@Inject Console console;
void run() {
Int64[] tests = [0, 1, 5, 50, 9000];
Int longestInt = tests.map(n -> n.estimateStringLength())
.reduce(0, (max, len) -> max.notLessThan(len));
Int longestBin = tests.map(n -> (64-n.leadingZeroCount).notLessThan(1))
.reduce(0, (max, len) -> max.maxOf(len));
function String(Int64) num = n -> {
Int indent = longestInt - n.estimateStringLength();
return $"{' ' * indent}{n}";
};
function String(Int64) bin = n -> {
Int index = n.leadingZeroCount.minOf(63);
Int indent = index - (64 - longestBin);
val bits = n.toBitArray()[index ..< 64];
return $"{' ' * indent}{bits.toString().substring(2)}";
};
for (Int64 test : tests) {
console.print($"The decimal value {num(test)} should produce an output of {bin(test)}");
}
}
}
</syntaxhighlight>
{{out}}
<pre>
The decimal value 0 should produce an output of 0
The decimal value 1 should produce an output of 1
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
</pre>
=={{header|Elena}}==
ELENA
<
import extensions;
public program()
{
new int[]{5,50,9000}.forEach::(n)
{
console.printLine(n.toString(2))
}
}</
{{out}}
<pre>
Line 2,199 ⟶ 2,231:
=={{header|Elixir}}==
Use <code>Integer.to_string</code> with a base of 2:
<syntaxhighlight lang="elixir">
IO.puts Integer.to_string(5, 2)
</syntaxhighlight>
Or, using the pipe operator:
<syntaxhighlight lang="elixir">
5 |> Integer.to_string(2) |> IO.puts
</syntaxhighlight>
<syntaxhighlight lang="elixir">
[5,50,9000] |> Enum.each(fn n -> IO.puts Integer.to_string(n, 2) end)
</syntaxhighlight>
{{out}}
Line 2,215 ⟶ 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}}==
<
var c:""
while a>0 do
Line 2,233 ⟶ 2,307:
iter Value of List do
log(Value+": "+bin(Value,false))
cls</
{{out}}
<pre>
Line 2,240 ⟶ 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>
{{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,249 ⟶ 2,335:
=={{header|Euphoria}}==
<
sequence s
s = {}
Line 2,261 ⟶ 2,347:
puts(1, toBinary(5) & '\n')
puts(1, toBinary(50) & '\n')
puts(1, toBinary(9000) & '\n')</
=== Functional/Recursive ===
<
include std/convert.e
Line 2,279 ⟶ 2,365:
printf(1, "%d\n", Bin(5))
printf(1, "%d\n", Bin(50))
printf(1, "%d\n", Bin(9000))</
=={{header|F Sharp|F#}}==
By translating C#'s approach, using imperative coding style (inflexible):
<
for i in [5; 50; 9000] do printfn "%s" <| Convert.ToString (i, 2)</
Alternatively, by creating a function <code>printBin</code> which prints in binary (more flexible):
<
// define the function
Line 2,296 ⟶ 2,381:
// use the function
[5; 50; 9000]
|> List.iter printBin</
Or more idiomatic so that you can use it with any printf-style function and the <code>%a</code> format specifier (most flexible):
<
open System.IO
Line 2,309 ⟶ 2,394:
// use it with printfn with %a
[5; 50; 9000]
|> List.iter (printfn "binary: %a" bin)</
Output (either version):
<pre>
Line 2,316 ⟶ 2,401:
10001100101000
</pre>
=={{header|Factor}}==
<
5 >bin print
50 >bin print
9000 >bin print</
=={{header|FALSE}}==
<
5 b;!
50 b;!
9000 b;!</
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|FBSL}}==
<
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,348 ⟶ 2,430:
pause
</syntaxhighlight>
=={{header|FOCAL}}==
<
01.20 S A=50;D 2
01.30 S A=9000;D 2
Line 2,365 ⟶ 2,446:
02.50 I (-BX)2.4;T !;R
02.60 I (-BD(BX))2.7;T "0";R
02.70 T "1"</
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|Forth}}==
<
\ HEX is a standard word to change the value of base to 16
Line 2,391 ⟶ 2,471:
decimal
</syntaxhighlight>
{{out}}
Line 2,400 ⟶ 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">
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sun May 19 23:14:14
Line 2,461 ⟶ 2,540:
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.
<
{$mode ISO}
Line 2,488 ⟶ 2,566:
writeLn(binaryNumber(50));
writeLn(binaryNumber(9000));
end.</
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}}==
<
' FreeBASIC v1.05.0 win64
Dim As String fmt = "#### -> &"
Line 2,502 ⟶ 2,579:
Sleep
End
</syntaxhighlight>
{{out}}
Line 2,510 ⟶ 2,587:
9000 -> 10001100101000
</pre>
=={{header|Frink}}==
The following all provide equivalent output. Input can be arbitrarily-large integers.
<
9000 -> binary
9000 -> base2
base2[9000]
base[9000, 2]
</syntaxhighlight>
=={{header|FunL}}==
<
println( n, bin(n) )</
{{out}}
Line 2,532 ⟶ 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">
fun main(x: i32): i64 =
loop (out = 0i64) = for i < 32 do
Line 2,544 ⟶ 2,618:
in out
in out
</syntaxhighlight>
=={{header|FutureBasic}}==
The decimal to binary conversion can be handled with a simple function.
<
include "NSLog.incl"
Line 2,566 ⟶ 2,638:
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Line 2,573 ⟶ 2,645:
9000 = 10001100101000
</pre>
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=03e84768e6ee2af9b7664efa04fa6da8 Click this link to run this code]'''
<
Dim siBin As Short[] = [5, 50, 9000]
Dim siCount As Short
Line 2,585 ⟶ 2,655:
Next
End</
{{out}}
<pre>
Line 2,592 ⟶ 2,662:
10001100101000
</pre>
=={{header|Go}}==
<
import (
Line 2,604 ⟶ 2,673:
fmt.Printf("%b\n", i)
}
}</
{{out}}
<pre>
Line 2,624 ⟶ 2,693:
1111
</pre>
=={{header|Groovy}}==
Solutions:
<
n binary
----- ---------------
Line 2,633 ⟶ 2,701:
[5, 50, 9000].each {
printf('%5d %15s\n', it, Integer.toBinaryString(it))
}</
{{out}}
<pre> n binary
Line 2,640 ⟶ 2,708:
50 110010
9000 10001100101000</pre>
=={{header|Haskell}}==
<
import Numeric
import Text.Printf
-- Use the built-in function showBin.
toBin n = showBin n ""
-- Use the built-in function showIntAtBase.
Line 2,665 ⟶ 2,735:
main = do
putStrLn $ printf "%4s %14s %14s" "N" "toBin" "toBin1"
mapM_ printToBin [5, 50, 9000]</
{{out}}
<pre>
Line 2,677 ⟶ 2,747:
and in terms of first and swap, we could also write this as:
<
import Data.List (unfoldr)
import Data.Tuple (swap)
Line 2,699 ⟶ 2,769:
)
)
[5, 50, 9000]</
{{Out}}
<pre>5 -> 101
Line 2,707 ⟶ 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.
<
every i := 5 | 50 | 255 | 1285 | 9000 do
write(i," = ",binary(i))
Line 2,729 ⟶ 2,799:
}
return reverse(trim(b,"0")) # nothing extraneous
end</
{{out}}
<pre>5 = 101
Line 2,736 ⟶ 2,806:
1285 = 10100000101
9000 = 10001100101000</pre>
=={{header|Idris}}==
<
binaryDigit : Integer -> Char
Line 2,756 ⟶ 2,825:
putStrLn (binaryString 50)
putStrLn (binaryString 9000)
</syntaxhighlight>
{{out}}
<pre>
Line 2,764 ⟶ 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=: '01'{~#:
tobin 5
101
Line 2,772 ⟶ 2,841:
110010
tobin 9000
10001100101000</
Uses implicit output.
=={{header|Java}}==
<p>
The <code>Integer</code> class offers the <code>toBinaryString</code> method.
</p>
<syntaxhighlight lang="java">
</syntaxhighlight>
<syntaxhighlight lang="java">
Integer.toBinaryString(50);
</syntaxhighlight>
<syntaxhighlight lang="java">
Integer.toBinaryString(9000);
</syntaxhighlight>
<p>
If you printed these values you would get the following.
</p>
<pre>
101
110010
10001100101000
</pre>
=={{header|JavaScript}}==
===ES5===
<
return new Number(number)
.toString(2);
Line 2,800 ⟶ 2,876:
// alert() in a browser, wscript.echo in WSH, etc.
print(toBinary(demoValues[i]));
}</
===ES6===
The simplest showBinary (or showIntAtBase), using default digit characters, would use JavaScript's standard String.toString(base):
<
"use strict";
Line 2,828 ⟶ 2,904:
// MAIN ---
return main();
})();</
{{Out}}
<pre>5 -> 101
Line 2,836 ⟶ 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:
<
"use strict";
Line 2,891 ⟶ 2,967:
// MAIN ---
return main();
})();</
{{Out}}
<pre>5 -> 一〇一
50 -> 一一〇〇一〇
9000 -> 一〇〇〇一一〇〇一〇一〇〇〇</pre>
=={{header|Joy}}==
<syntaxhighlight lang="joy">DEFINE bin == "" [pop 1 >] [[2 div "01" of] dip cons] while ["01" of] dip cons.
[0 1 2 5 50 9000] [bin] map put.</syntaxhighlight>
{{out}}
<pre>["0" "1" "10" "101" "110010" "10001100101000"]</pre>
=={{header|jq}}==
<
[ recurse( ./2 | floor; . > 0) % 2 ] | reverse | join("") ;
# The task:
(5, 50, 9000) | binary_digits</
{{Out}}
$ jq -n -r -f Binary_digits.jq
Line 2,921 ⟶ 2,990:
110010
10001100101000
=={{header|Julia}}==
{{works with|Julia|1.0}}
<
for n in (0, 5, 50, 9000)
Line 2,935 ⟶ 3,003:
for n in (0, 5, 50, 9000)
@printf("%6i → %s\n", n, string(n, base=2, pad=20))
end</
{{out}}
Line 2,948 ⟶ 3,016:
50 → 00000000000000110010
9000 → 00000010001100101000</pre>
=={{header|K}}==
<
tobin' 5 50 9000
("101"
"110010"
"10001100101000")</
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">
fun main() {
val numbers = intArrayOf(5, 50, 9000)
numbers.forEach { println("$it -> ${it.toString(2)}") }
}</
{{out}}
<pre>
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}}==
<
{def dec2bin
{lambda {:dec}
Line 2,994 ⟶ 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}}==
<
[5 50 9000] [3 1] reshape .</
{{out}}
<pre>[
Line 3,006 ⟶ 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:
<
(: 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:
<
(: lists foreach
(lambda (x)
Line 3,022 ⟶ 3,118:
(list (: erlang integer_to_list x 2))))
(list 5 50 9000))
</syntaxhighlight>
{{out|note=for both examples}}
<pre>
Line 3,029 ⟶ 3,125:
10001100101000
</pre>
=={{header|Liberty BASIC}}==
<
print a;"=";dec2bin$(a)
next
Line 3,046 ⟶ 3,141:
wend
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 man computer">
// Little Man Computer, for Rosetta Code.
// Read numbers from user and display them in binary.
Line 3,112 ⟶ 3,206:
nrDigits DAT
diff DAT
</syntaxhighlight>
{{out}}
<pre>
Line 3,119 ⟶ 3,213:
900->1110000100
</pre>
=={{header|LLVM}}==
{{trans|C}}
<
; source_filename = "binary.c"
; target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
Line 3,302 ⟶ 3,394:
!0 = !{i32 1, !"wchar_size", i32 2}
!1 = !{i32 7, !"PIC Level", i32 2}
!2 = !{!"clang version 6.0.1 (tags/RELEASE_601/final)"}</
{{out}}
<pre>0
Line 3,324 ⟶ 3,416:
10010
10011</pre>
=={{header|Locomotive Basic}}==
<
20 PRINT BIN$(50)
30 PRINT BIN$(9000)</
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|LOLCODE}}==
<
HOW IZ I DECIMULBINUR YR DECIMUL
I HAS A BINUR ITZ ""
Line 3,350 ⟶ 3,440:
VISIBLE I IZ DECIMULBINUR YR 50 MKAY
VISIBLE I IZ DECIMULBINUR YR 9000 MKAY
KTHXBYE</
{{out}}
Line 3,359 ⟶ 3,449:
=={{header|Lua}}==
===Lua - Iterative===
<syntaxhighlight lang
local bin = ""
while n >
bin = n % 2 .. bin
n = math.floor(n / 2)
end
return n .. bin
end
print(dec2bin(5))
print(dec2bin(50))
print(dec2bin(9000))</
{{out}}
<pre>101
110010
10001100101000</pre>
===Lua - Recursive===
{{works with|Lua|5.3+}}
<syntaxhighlight lang="lua">-- for Lua 5.1/5.2 use math.floor(n/2) instead of n>>1, and n%2 instead of n&1
function dec2bin(n)
return n>1 and dec2bin(n>>1)..(n&1) or n
end
print(dec2bin(5))
print(dec2bin(50))
print(dec2bin(9000))</
{{out}}
<pre>101
Line 3,391 ⟶ 3,483:
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Form 90, 40
Line 3,445 ⟶ 3,537:
}
Checkit
</syntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 3,459 ⟶ 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,465 ⟶ 3,587:
matches the binary representation of the input, e.g. <code>BINARY.(5)</code> is <code>101</code>.
<
INTERNAL FUNCTION(NUM)
Line 3,485 ⟶ 3,607:
VECTOR VALUES FMT = $I4,2H: ,I16*$
END OF PROGRAM </
{{out}}
<pre> 5: 101
Line 3,492 ⟶ 3,614:
=={{header|Maple}}==
<syntaxhighlight lang="maple">
> convert( 50, 'binary' );
110010
> convert( 9000, 'binary' );
10001100101000
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
=={{header|MATLAB}} / {{header|Octave}}==
<
dec2bin(50)
dec2bin(9000) </
The output is a string containing ascii(48) (i.e. '0') and ascii(49) (i.e. '1').
=={{header|Maxima}}==
<
[n: first(arg), b: if length(arg) > 1 then second(arg) else 10, v: [ ], q],
do (
Line 3,520 ⟶ 3,639:
/*
10001100101000
*/</
=={{header|MAXScript}}==
<
-- MAXScript: Output decimal numbers from 0 to 16 as Binary : N.H. 2019
for k = 0 to 16 do
Line 3,546 ⟶ 3,664:
print binString
)
</syntaxhighlight>
{{out}}
Output to MAXScript Listener:
Line 3,568 ⟶ 3,686:
"10000"
</pre>
=={{header|Mercury}}==
<
:- interface.
Line 3,586 ⟶ 3,703:
print_binary_digits(N, !IO) :-
io.write_string(int_to_base_string(N, 2), !IO),
io.nl(!IO).</
=={{header|min}}==
{{works with|min|0.
<syntaxhighlight lang="min">(
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>
{{out}}
<pre>0, 1, 10, 101, 110010, 10001100101000</pre>
=={{header|MiniScript}}==
=== Iterative ===
<
result = ""
while n
Line 3,622 ⟶ 3,732:
print binary(50)
print binary(9000)
print binary(0)</
=== Recursive ===
<
if n == 0 then
if result == "" then return "0" else return result
Line 3,636 ⟶ 3,746:
print binary(50)
print binary(9000)
print binary(0)</
{{out}}
<pre>
Line 3,644 ⟶ 3,754:
0
</pre>
=={{header|mLite}}==
<
(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>
==== from the REPL ====
Line 3,661 ⟶ 3,770:
> binary 9000;
"10001100101000"</pre>
=={{header|Modula-2}}==
<
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT Write,WriteLn,ReadChar;
Line 3,691 ⟶ 3,799:
ReadChar
END Binary.</
=={{header|Modula-3}}==
<
IMPORT IO, Fmt;
Line 3,704 ⟶ 3,811:
num := 150;
IO.Put(Fmt.Int(num, 2) & "\n");
END Binary.</
{{out}}
<pre>
Line 3,710 ⟶ 3,817:
10010110
</pre>
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
Line 3,729 ⟶ 3,835:
w_ = list.word(n_)
say w_.right(20)':' getBinaryDigits(w_)
end n_</
{{out}}
<pre>
Line 3,737 ⟶ 3,843:
9000: 10001100101000
</pre>
=={{header|NewLisp}}==
<syntaxhighlight lang="newlisp">
;;; Using the built-in "bits" function
;;; For integers up to 9,223,372,036,854,775,807
Line 3,753 ⟶ 3,858:
;;; Example
(println (big-bits 1234567890123456789012345678901234567890L))
</syntaxhighlight>
<pre>
Output:
Line 3,762 ⟶ 3,867:
1110100000110010010010000001110101110000001101101111110011101110001010110010111100010111111001011011001110001111110000101011010010
</pre>
=={{header|Nickle}}==
Using the Nickle output radix operator:
Line 3,775 ⟶ 3,879:
> 9000 # 2
10001100101000</pre>
=={{header|Nim}}==
<
## Calculates how many digits `x` has when each digit covers `r` bits.
result = 1
Line 3,800 ⟶ 3,903:
for i in 0..15:
echo toBin(i)</
{{out}}
<pre>0
Line 3,820 ⟶ 3,923:
===Version using strformat===
<
for n in 0..15:
echo fmt"{n:b}"</
{{out}}
Line 3,842 ⟶ 3,945:
1110
1111</pre>
=={{header|Oberon-2}}==
<
MODULE BinaryDigits;
IMPORT Out;
Line 3,862 ⟶ 3,964:
OutBin(42); Out.Ln;
END BinaryDigits.
</syntaxhighlight>
{{out}}
Line 3,872 ⟶ 3,974:
101010
</pre>
=={{header|Objeck}}==
<
function : Main(args : String[]) ~ Nil {
5->ToBinaryString()->PrintLine();
Line 3,880 ⟶ 3,981:
9000->ToBinaryString()->PrintLine();
}
}</
{{out}}
<pre>
Line 3,887 ⟶ 3,988:
10001100101000
</pre>
=={{header|OCaml}}==
<
let last_digit n = [|"0"; "1"|].(n land 1) in
let rec aux lst = function
in
String.concat "" (aux [last_digit d] (d lsr 1))
(* test *)
|> List.map bin_of_int |> String.concat ", " |> 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,919 ⟶ 4,023:
ok
</pre>
=={{header|Ol}}==
<
(print (number->string 5 2))
(print (number->string 50 2))
(print (number->string 9000 2))
</syntaxhighlight>
{{Out}}
<pre>
Line 3,932 ⟶ 4,035:
10001100101000
</pre>
=={{header|OxygenBasic}}==
The Assembly code uses block structures to minimise the use of labels.
<
function BinaryBits(sys n) as string
Line 3,979 ⟶ 4,081:
print BinaryBits 0xaa 'result 10101010
</syntaxhighlight>
=={{header|Panda}}==
<syntaxhighlight lang
{{out}}
<pre>0
Line 4,000 ⟶ 4,101:
1110
1111</pre>
=={{header|PARI/GP}}==
<
=={{header|Pascal}}==
{{works with|Free Pascal}}
FPC compiler Version 2.6 upwards.The obvious version.
<
{$MODE objFPC}
uses
Line 4,035 ⟶ 4,134:
IntBinTest(5);IntBinTest(50);IntBinTest(5000);
IntBinTest(0);IntBinTest(NativeUint(-1));
end.</
{{out}}
<pre> 5 101
Line 4,047 ⟶ 4,146:
Beware of the endianess of the constant.
I check performance with random Data.
<
program IntToPcharTest;
uses
Line 4,153 ⟶ 4,252:
Writeln(cnt/rounds+1:6:3);
FreeMem(s);
end.</
{{out}}
<pre>
Line 4,167 ⟶ 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}}==
<
<@ saybaslit>0</@>
Line 4,175 ⟶ 4,273:
<@ saybaslit>50</@>
<@ saybaslit>9000</@>
</syntaxhighlight>
=={{header|Perl}}==
<
printf "%b\n", $_;
}</
<pre>
101
Line 4,186 ⟶ 4,283:
10001100101000
</pre>
=={{header|Phix}}==
<!--<
<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>
<!--</
{{out}}
<pre>
Line 4,199 ⟶ 4,295:
10001100101000
</pre>
=={{header|Phixmonti}}==
<
"The decimal value " print dup print " should produce an output of " print
20 int>bit
Line 4,223 ⟶ 4,318:
5 printBinary
50 printBinary
9000 printBinary</
Other solution
<
by Galileo, 05/2022 #/
Line 4,244 ⟶ 4,339:
50 printBinary
9000 printBinary
</syntaxhighlight>
{{out}}
<pre>The decimal value 5 should produce an output of 101
Line 4,251 ⟶ 4,346:
=== Press any key to exit ===</pre>
=={{header|PHP}}==
<
echo decbin(5);
echo decbin(50);
echo decbin(9000);</
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|Picat}}==
<
println(to_binary_string(I))
end.</
{{out}}
Line 4,271 ⟶ 4,364:
110010
1110000100</pre>
=={{header|PicoLisp}}==
<
-> "101"
Line 4,281 ⟶ 4,372:
: (bin 9000)
-> "10001100101000"</
=={{header|Piet}}==
Line 4,440 ⟶ 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:
<
{{out}}
<pre>Output: 0011001
</pre>
With leading zero suppression:
<
put string(text) edit (25) (b);
Line 4,454 ⟶ 4,543:
put string(text) edit (2147483647) (b);
put skip list (trim(text, '0'));</
{{out}}
<pre>
Line 4,460 ⟶ 4,549:
1111111111111111111111111111111
</pre>
=={{header|PL/M}}==
<
/* CP/M BDOS CALL */
Line 4,497 ⟶ 4,585:
CALL BDOS(0,0);
EOF</
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|PowerBASIC}}==
Pretty simple task in PowerBASIC since it has a built-in BIN$-Function. Omitting the second parameter ("Digits") means no leading zeros in the result.
<
#COMPILE EXE
#DIM ALL
Line 4,517 ⟶ 4,604:
PRINT STR$(d(i)) & ": " & BIN$(d(i)) & " (" & BIN$(d(i), 32) & ")"
NEXT i
END FUNCTION</
{{out}}<pre>
5: 101 (00000000000000000000000000000101)
Line 4,523 ⟶ 4,610:
9000: 10001100101000 (00000000000000000010001100101000)
</pre>
=={{header|PowerShell}}==
{{libheader|Microsoft .NET Framework}}
<
{{out}}
<pre>101
110010
1110000100</pre>
=={{header|Processing}}==
<
println(Integer.toBinaryString(50)); // 110010
println(Integer.toBinaryString(9000)); // 10001100101000</
Processing also has a binary() function, but this returns zero-padded results
<
println(binary(50)); // 00000000110010
println(binary(9000)); // 10001100101000</
=={{header|Prolog}}==
{{works with|SWI Prolog}}
{{works with|GNU Prolog}}
<
binary(X) :- format('~2r~n', [X]).
main :- maplist(binary, [5,50,9000]), halt.
</syntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|PureBasic}}==
<
PrintN(Bin(5)) ;101
PrintN(Bin(50)) ;110010
Line 4,561 ⟶ 4,644:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|Python}}==
===String.format() method===
{{works with|Python|3.X and 2.6+}}
<
0
Line 4,587 ⟶ 4,669:
1101
1110
1111</
===Built-in bin() function===
{{works with|Python|3.X and 2.6+}}
<
0
Line 4,608 ⟶ 4,690:
1101
1110
1111</
Pre-Python 2.6:
<
>>> 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,629 ⟶ 4,711:
1101
1110
1111</
===Custom functions===
Defined in terms of a more general '''showIntAtBase''' function:
<
Line 4,723 ⟶ 4,805:
if __name__ == '__main__':
main()</
{{Out}}
<pre>Mapping showBinary over integer list:
Line 4,737 ⟶ 4,819:
Or, using a more specialised function to decompose an integer to a list of boolean values:
<
Line 4,857 ⟶ 4,939:
# MAIN -------------------------------------------------
if __name__ == '__main__':
main()</
{{Out}}
<pre>Mapping a composed function:
Line 4,868 ⟶ 4,950:
50 -> 110010
9000 -> 10001100101000</pre>
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
Print DecToBin$(5)
Print DecToBin$(50)
Line 4,921 ⟶ 5,002:
</syntaxhighlight>
=={{header|Quackery}}==
Quackery provides built-in radix control, much like Forth.
<
2 base put ( Numbers will be output in base 2 now. )
( Bases from 2 to 36 (inclusive) are supported. )
Line 4,935 ⟶ 5,015:
base release ( It's best to clean up after ourselves. )
( Numbers will be output in base 10 now. )
</syntaxhighlight>
A user-defined conversion might look something like this:
<
[ [] swap
[ 2 /mod digit
Line 4,949 ⟶ 5,029:
50 bin echo$ cr
9000 bin echo$ cr
</syntaxhighlight>
{{out}}
<pre>
Line 4,956 ⟶ 5,036:
10001100101000
</pre>
=={{header|R}}==
<
dec2bin <- function(num) {
ifelse(num == 0,
Line 4,969 ⟶ 5,048:
cat(dec2bin(anumber),"\n")
}
</syntaxhighlight>
'''output'''
<pre>
Line 4,977 ⟶ 5,056:
10001100101000
</pre>
=={{header|Racket}}==
<
#lang racket
;; Option 1: binary formatter
Line 4,985 ⟶ 5,063:
;; Option 2: explicit conversion
(for ([i 16]) (displayln (number->string i 2)))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku"
<pre>
101
Line 4,999 ⟶ 5,076:
Alternatively:
<syntaxhighlight lang="raku"
<pre>101
110010
10001100101000</pre>
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
'Convert Integer to binary string
Print "bin 5 = ", bin$(5)
Line 5,011 ⟶ 5,087:
Print "bin 9000 = ",bin$(9000)
sleep 10
</syntaxhighlight>
=={{header|Red}}==
<
foreach number [5 50 9000] [
Line 5,021 ⟶ 5,096:
print reduce [ pad/left number 5 binstr ]
]
</syntaxhighlight>
'''output'''
<pre> 5 101
Line 5,027 ⟶ 5,102:
9000 10001100101000
</pre>
=={{header|Retro}}==
<
=={{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,036 ⟶ 5,130:
Note: some REXX interpreters have a '''D2B''' [Decimal to Binary] BIF ('''b'''uilt-'''i'''n '''f'''unction).
<br>Programming note: this REXX version depends on '''numeric digits''' being large enough to handle leading zeroes in this manner (by adding a zero (to the binary version) to force superfluous leading zero suppression).
<
numeric digits 1000 /*ensure we can handle larger numbers. */
@.=; @.1= 0
Line 5,046 ⟶ 5,140:
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. */</
{{out|output}}
<pre>
Line 5,058 ⟶ 5,152:
This version handles the case of zero as a special case more elegantly.
<br>The following versions depend on the setting of '''numeric digits''' such that the number in decimal can be expressed as a whole number.
<
@.=; @.1= 0
@.2= 5
Line 5,068 ⟶ 5,162:
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. */</
{{out|output|text= 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.
<
@.=; @.1= 0
@.2= 5
Line 5,082 ⟶ 5,176:
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. */</
{{out|output|text= 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).
<
numeric digits 200 /*ensure we can handle larger numbers. */
@.=; @.1= 0
Line 5,100 ⟶ 5,194:
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. */</
{{out|output}}
<pre>
Line 5,112 ⟶ 5,206:
=={{header|Ring}}==
<
see "Number to convert : "
give a
Line 5,125 ⟶ 5,219:
else see 0 ok
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}}==
<
puts "%b" % n
end</
or
<
puts n.to_s(2)
end</
{{out}}
<pre>101
Line 5,141 ⟶ 5,263:
=={{header|Run BASIC}}==
<
while 2^(n+1) < a
n = n + 1
Line 5,154 ⟶ 5,276:
print 0;
end if
next</
{{out}}
<pre>Number to convert:?9000
10001100101000</pre>
=={{header|Rust}}==
<
for i in 0..8 {
println!("{:b}", i)
}
}</
Outputs:
<pre>0
Line 5,174 ⟶ 5,295:
110
111</pre>
=={{header|S-lang}}==
<
{
variable m = 0x40000000, prn = 0, bs = "";
Line 5,196 ⟶ 5,316:
() = printf("%s\n", int_to_bin(5));
() = printf("%s\n", int_to_bin(50));
() = printf("%s\n", int_to_bin(9000));</
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|S-BASIC}}==
<syntaxhighlight lang = "BASIC">
rem - Return binary representation of n
function bin$(n = integer) = string
var s = string
s = ""
while n > 0 do
begin
if (n - (n / 2) * 2) = 0 then
s = "0" + s
else
s = "1" + s
n = n / 2
end
end = s
rem - exercise the function
print "5 = "; bin$(5)
print "50 = "; bin$(50)
print "9000 = "; bin$(9000)
end
</syntaxhighlight>
{{out}}
<pre>
5 = 101
50 = 110010
9000 = 10001100101000
</pre>
=={{header|Scala}}==
Scala has an implicit conversion from <code>Int</code> to <code>RichInt</code> which has a method <code>toBinaryString</code>.
<
res0: String = 101
Line 5,211 ⟶ 5,364:
scala> (9000 toBinaryString)
res2: String = 10001100101000</
=={{header|Scheme}}==
<
(display (number->string 50 2)) (newline)
(display (number->string 9000 2)) (newline)</
=={{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.
<
const proc: main is func
Line 5,230 ⟶ 5,421:
writeln(number radix 2);
end for;
end func;</
{{out}}
<pre>
Line 5,251 ⟶ 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}}==
<
toBinaryString(number(0)) :=
Line 5,261 ⟶ 5,467:
toBinaryString(floor(number/2)) ++ val when floor(number/2) > 0
else
val;</
{{out}}
Line 5,269 ⟶ 5,475:
=={{header|Sidef}}==
<
say n.as_bin;
}</
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|Simula}}==
<
PROCEDURE OUTINTBIN(N); INTEGER N;
Line 5,292 ⟶ 5,497:
END;
END</
{{out}}
<pre>
Line 5,299 ⟶ 5,504:
10001100101000
</pre>
=={{header|SkookumScript}}==
<
println(50.binary)
println(9000.binary)</
Or looping over a list of numbers:
<
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|Smalltalk}}==
<
50 printOn: Stdout radix:2
9000 printOn: Stdout radix:2</
or:
<
=={{header|SNOBOL4}}==
<
define('bin(n,r)') :(bin_end)
bin bin = le(n,0) r :s(return)
Line 5,329 ⟶ 5,531:
output = bin(50)
output = bin(9000)
end</
{{out}}
<pre>
Line 5,336 ⟶ 5,538:
10001100101000
</pre>
=={{header|SNUSP}}==
<syntaxhighlight lang="snusp">
/recurse\
$,binary!\@\>?!\@/<@\.#
Line 5,344 ⟶ 5,545:
/<+>- \ div2
\?!#-?/+# mod2
</syntaxhighlight>
=={{header|Standard ML}}==
<
print (Int.fmt StringCvt.BIN 50 ^ "\n");
print (Int.fmt StringCvt.BIN 9000 ^ "\n");</
=={{header|Swift}}==
<
println(String(num, radix: 2))
}</
{{out}}
<pre>
Line 5,360 ⟶ 5,559:
110010
10001100101000</pre>
=={{header|Tcl}}==
<
# 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"
}</
Demonstrating:
<
puts [num2bin $x]
}
Line 5,375 ⟶ 5,573:
puts [num2bin 5]
puts [num2bin 50]
puts [num2bin 9000]</
{{out}}
<pre>
Line 5,401 ⟶ 5,599:
<br>
Or you can use the builtin format:
<
puts [format "%4u: %b" $n $n]
}</
{{out}}
<pre> 0: 0
Line 5,410 ⟶ 5,608:
50: 110010
9000: 10001100101000</pre>
=={{header|TI-83 BASIC}}==
Using Standard TI-83 BASIC
<
:Disp "NUMBER TO"
:Disp "CONVERT:"
Line 5,431 ⟶ 5,628:
:N-1→N
:End
:Disp B</
Alternate using a string to display larger numbers.
<
:Input X
:" "→Str1
Line 5,441 ⟶ 5,638:
:iPart(X)→X
:End
:Str1</
Using the baseInput() "real(25," function from [http://www.detachedsolutions.com/omnicalc/ Omnicalc]
<
:Disp "NUMBER TO"
:Disp "CONVERT"
:Input "Str1"
:Disp real(25,Str1,10,2)</
More compact version:
<
:" →Str1
:If not(D:"0→Str1
Line 5,462 ⟶ 5,659:
:End
: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,498 ⟶ 5,694:
130 Print "D"; : Return
140 Print "E"; : Return
150 Print "F"; : Return</
{{out}}
<pre>Enter base (1<X<17): 2
Line 5,507 ⟶ 5,703:
=={{header|UNIX Shell}}==
Since POSIX does not specify local variables, make use of <code>set</code> for highest portability.
<syntaxhighlight lang="sh">bin() {
set -- "${1:-0}" ""
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>
{{out}}
<pre>0 1 10 101 110010 10001100101000</pre>
=={{header|VBA}}==
Line 5,537 ⟶ 5,737:
Places is useful for padding the return value with leading 0s (zeros).
<syntaxhighlight lang="vb">
Option Explicit
Line 5,576 ⟶ 5,776:
End If
End Function
</syntaxhighlight>
{{out}}
<pre>The decimal value 5 should produce an output of : 101
Line 5,584 ⟶ 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.
<
#10 = Get_Num("Give a numeric value, -1 to end: ", STATLINE)
if (#10 < 0) { break }
Line 5,603 ⟶ 5,802:
EOL
Ins_Newline
Return </
Example output when values 0, 1, 5, 50 and 9000 were entered:
<pre>
Line 5,612 ⟶ 5,811:
10001100101000
</pre>
=={{header|Vim Script}}==
<
let n = a:n
let s = ""
Line 5,634 ⟶ 5,832:
echo Num2Bin(5)
echo Num2Bin(50)
echo Num2Bin(9000)</
{{Out}}
Line 5,640 ⟶ 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,678 ⟶ 5,875:
Debug.Print Bin(9000)
End Sub
</syntaxhighlight>
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|Visual Basic .NET}}==
<
Sub Main
For Each number In {5, 50, 9000}
Line 5,691 ⟶ 5,887:
Next
End Sub
End Module</
{{out}}
<pre>101
110010
10001100101000</pre>
=={{header|Visual FoxPro}}==
<
*!* Binary Digits
CLEAR
Line 5,724 ⟶ 5,919:
RETURN FLOOR(v)
ENDFUNC
</syntaxhighlight>
{{out}}
<pre>
Line 5,731 ⟶ 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,736 ⟶ 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">
Line 5,775 ⟶ 6,052:
</
It was generated from the following pseudo-Assembly.
<
; Increment indefinitely.
0:
Line 5,811 ⟶ 6,088:
3:
pop
ret</
=={{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:
<
; the following function also casts the string to a number
^(@+ \.toString 2)</
To output to the console:
<
Outputs: <pre>
101
110010
1110000100</pre>
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<
System.print("Converting to binary:")
for (i in [5, 50, 9000]) Fmt.print("$d -> $b", i, i)</
{{out}}
Line 5,890 ⟶ 6,118:
=={{header|X86 Assembly}}==
Translation of XPL0. Assemble with tasm, tlink /t
<
.code
.486
Line 5,918 ⟶ 6,146:
int 29h ;display character
ret
end start</
{{out}}
Line 5,926 ⟶ 6,154:
10001100101000
</pre>
=={{header|XPL0}}==
<
proc BinOut(N); \Output N in binary
Line 5,944 ⟶ 6,171:
I:= I+1;
until KeyHit or I=0;
]</
{{out}}
Line 5,963 ⟶ 6,190:
100000010100001
</pre>
=={{header|Yabasic}}==
<
a(0) = 5
a(1) = 50
Line 5,973 ⟶ 6,199:
print a(i) using "####", " -> ", bin$(a(i))
next i
end</
=={{header|Z80 Assembly}}==
{{trans|8086 Assembly}}
<
PrintChar equ &BB5A ;syscall - prints accumulator to Amstrad CPC's screen
Line 6,050 ⟶ 6,275:
call &BB5A
ld a,10
jp &BB5A ;its ret will return for us.</
This is another version. Output of the result over port 0A hex.
<
; HL contains the value to be converted
ld hl,5
Line 6,100 ⟶ 6,325:
djnz bitloop
ret</
=={{header|zkl}}==
<syntaxhighlight lang
<
<
=={{header|ZX Spectrum Basic}}==
<
20 LET n=50: GO SUB 1000: PRINT s$
30 LET n=9000: GO SUB 1000: PRINT s$
Line 6,123 ⟶ 6,344:
1070 IF (sf <> 0) THEN LET s$=s$+d$
1080 NEXT l
1090 RETURN</
|