Binary digits
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Create and display the sequence of binary digits for a given non-negative integer.
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
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
8th
2 base drop
#50 . cr
- Output:
110010
11l
L(n) [0, 5, 50, 9000]
print(‘#4 = #.’.format(n, bin(n)))
- Output:
0 = 0 5 = 101 50 = 110010 9000 = 10001100101000
360 Assembly
* Binary digits 27/08/2015
BINARY CSECT
USING BINARY,R12
LR R12,R15 set base register
BEGIN LA R10,4
LA R9,N
LOOPN MVC W,0(R9)
MVI FLAG,X'00'
LA R8,32
LA R2,CBIN
LOOP TM W,B'10000000' test fist bit
BZ ZERO zero
MVI FLAG,X'01' one written
MVI 0(R2),C'1' write 1
B CONT
ZERO CLI FLAG,X'01' is one written ?
BNE BLANK
MVI 0(R2),C'0' write 0
B CONT
BLANK BCTR R2,0 backspace
CONT L R3,W
SLL R3,1 shilf left
ST R3,W
LA R2,1(R2) next bit
BCT R8,LOOP loop on bits
PRINT CLI FLAG,X'00' is '0'
BNE NOTZERO
MVI 0(R2),C'0' then write 0
NOTZERO L R1,0(R9)
XDECO R1,CDEC
XPRNT CDEC,45
LA R9,4(R9)
BCT R10,LOOPN loop on numbers
RETURN XR R15,R15 set return code
BR R14 return to caller
N DC F'0',F'5',F'50',F'9000'
W DS F work
FLAG DS X flag for trailing blanks
CDEC DS CL12 decimal value
DC C' '
CBIN DC CL32' ' binary value
YREGS
END BINARY
- Output:
0 0 5 101 50 110010 9000 10001100101000
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:
- Output:
Note that 0815 reads numeric input in hexadecimal.
echo -e "5\n32\n2329" | 0815 bin.0
101
110010
10001100101001
6502 Assembly
This example has been written for the C64 and uses some BASIC routines to read the parameter after the SYS command and to print the result. Compile with the Turbo Macro Pro cross assembler:
tmpx -i dec2bin.s -o dec2bin.prg
Use the c1541 utility to create a disk image that can be loaded using VICE x64. Run with:
SYS828,x
where x is an integer ranging from 0 to 65535 (16 bit int). Floating point numbers are truncated and converted accordingly. The example can easily be modified to run on the VIC-20, just change the labels as follows:
chkcom = $cefd frmnum = $cd8a getadr = $d7f7 strout = $cb1e
; C64 - Binary digits
; http://rosettacode.org/wiki/Binary_digits
; *** labels ***
declow = $fb
dechigh = $fc
binstrptr = $fd ; $fe is used for the high byte of the address
chkcom = $aefd
frmnum = $ad8a
getadr = $b7f7
strout = $ab1e
; *** main ***
*=$033c ; sys828 tbuffer ($033c-$03fb)
jsr chkcom ; check for and skip comma
jsr frmnum ; evaluate numeric expression
jsr getadr ; convert floating point number to two-byte int
jsr dec2bin ; convert two-byte int to binary string
lda #<binstr ; load the address of the binary string - low
ldy #>binstr ; high byte
jsr skiplz ; skip leading zeros, return an address in a/y
; that points to the first "1"
jsr strout ; print the result
rts
; *** subroutines ****
; Converts a 16 bit integer to a binary string.
; Input: y - low byte of the integer
; a - high byte of the integer
; Output: a 16 byte string stored at 'binstr'
dec2bin sty declow ; store the two-byte integer
sta dechigh
lda #<binstr ; store the binary string address on the zero page
sta binstrptr
lda #>binstr
sta binstrptr+1
ldx #$01 ; start conversion with the high byte
wordloop ldy #$00 ; bit counter
byteloop asl declow,x ; shift left, bit 7 is shifted into carry
bcs one ; carry set? jump
lda #"0" ; a="0"
bne writebit
one lda #"1" ; a="1"
writebit sta (binstrptr),y ; write the digit to the string
iny ; y++
cpy #$08 ; y==8 all bits converted?
bne byteloop ; no -> convert next bit
clc ; clear carry
lda #$08 ; a=8
adc binstrptr ; add 8 to the string address pointer
sta binstrptr
bcc nooverflow ; address low byte did overflow?
inc binstrptr+1 ; yes -> increase the high byte
nooverflow dex ; x--
bpl wordloop ; x<0? no -> convert the low byte
rts ; yes -> conversion finished, return
; Skip leading zeros.
; Input: a - low byte of the byte string address
; y - high byte -"-
; Output: a - low byte of string start address without leading zeros
; y - high byte -"-
skiplz sta binstrptr ; store the binary string address on the zero page
sty binstrptr+1
ldy #$00 ; byte counter
skiploop lda (binstrptr),y ; load a byte from the string
iny ; y++
cpy #$11 ; y==17
beq endreached ; yes -> end of string reached without a "1"
cmp #"1" ; a=="1"
bne skiploop ; no -> take the next byte
beq add2ptr ; yes -> jump
endreached dey ; move the pointer to the last 0
add2ptr clc
dey
tya ; a=y
adc binstrptr ; move the pointer to the first "1" in the string
bcc loadhigh ; overflow?
inc binstrptr+1 ; yes -> increase high byte
loadhigh ldy binstrptr+1
rts
; *** data ***
binstr .repeat 16, $00 ; reserve 16 bytes for the binary digits
.byte $0d, $00 ; newline + null terminator
- Output:
SYS828,5 101 SYS828,50 110010 SYS828,9000 10001100101000 SYS828,4.7 100
8080 Assembly
bdos: equ 5h ; CP/M system call
puts: equ 9h ; Print string
org 100h
lxi h,5 ; Print value for 5
call prbin
lxi h,50 ; Print value for 50
call prbin
lxi h,9000 ; Print value for 9000
prbin: call bindgt ; Make binary representation of HL
mvi c,puts ; Print it
jmp bdos
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Return the binary representation of the 16-bit number in HL
;;; as a string starting at [DE].
bindgt: lxi d,binend ; End of binary string
ana a ; Clear carry flag
binlp: dcx d ; Previous digit
mov a,h ; Shift HL left, LSB into carry flag
rar
mov h,a
mov a,l
rar
mov l,a
mvi a,'0' ; Digit '0' or '1' depending on
aci 0 ; status of carry flag.
stax d
mov a,h ; Is HL 0 now?
ora l
rz ; Then stop
jmp binlp ; Otherwise, do next bit
binstr: db '0000000000000000' ; Placeholder for string
binend: db 13,10,'$' ; end with \r\n
- Output:
101 110010 10001100101000
8086 Assembly
.model small
.stack 1024
.data
TestData0 byte 5,255 ;255 is the terminator
TestData1 byte 5,0,255
TestData2 byte 9,0,0,0,255
.code
start:
mov ax,@data
mov ds,ax
cld ;String functions are set to auto-increment
mov ax,2 ;clear screen by setting video mode to 0
int 10h ;select text mode - We're already in it, so this clears the screen
mov si,offset TestData0
call PrintBinary_NoLeadingZeroes
mov si,offset TestData1
call PrintBinary_NoLeadingZeroes
mov si,offset TestData2
call PrintBinary_NoLeadingZeroes
ExitDOS:
mov ax,4C00h ;return to dos
int 21h
PrintBinary_NoLeadingZeroes proc
;input: DS:SI = seg:offset of a 255-terminated sequence of unpacked BCD digits, stored big-endian
;setup
mov bx,8000h
;bl will be our "can we print zeroes yet" flag.
;bh is the "revolving bit mask" - we'll compare each bit to it, then rotate it right once.
; It's very handy because it's a self-resetting loop counter as well!
NextDigit:
lodsb
cmp al,255
je Terminated
NextBit:
test al,bh ;is the bit we're testing right now set?
jz PrintZero
;else, print one
push ax
mov dl,'1' ;31h
mov ah,2
int 21h ;prints the ascii code in DL
pop ax
or bl,1 ;set "we've printed a one" flag
jmp predicate
PrintZero:
test bl,bl
jz predicate
push ax
mov dl,'0' ;30h
mov ah,2
int 21h
pop ax
predicate:
ror bh,1
jnc NextBit
;if the carry is set, we've rotated BH back to 10000000b,
; so move on to the next digit in that case.
jmp NextDigit
Terminated:
push ax
mov ah,2
mov dl,13 ;carriage return
int 21h
mov dl,10 ;linefeed
int 21h
pop ax
ret
PrintBinary_NoLeadingZeroes endp
AArch64 Assembly
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program binarydigit.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
sMessAffBindeb: .asciz "The decimal value "
sMessAffBin: .asciz " should produce an output of "
szRetourLigne: .asciz "\n"
/*******************************************/
/* Uninitialized data */
/*******************************************/
.bss
sZoneConv: .skip 100
sZoneBin: .skip 100
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: /* entry of program */
mov x5,5
mov x0,x5
ldr x1,qAdrsZoneConv
bl conversion10S
mov x0,x5
ldr x1,qAdrsZoneBin
bl conversion2 // binary conversion and display résult
ldr x0,qAdrsZoneBin
ldr x0,qAdrsMessAffBindeb
bl affichageMess
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrsMessAffBin
bl affichageMess
ldr x0,qAdrsZoneBin
bl affichageMess
ldr x0,qAdrszRetourLigne
bl affichageMess
/* other number */
mov x5,50
mov x0,x5
ldr x1,qAdrsZoneConv
bl conversion10S
mov x0,x5
ldr x1,qAdrsZoneBin
bl conversion2 // binary conversion and display résult
ldr x0,qAdrsZoneBin
ldr x0,qAdrsMessAffBindeb
bl affichageMess
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrsMessAffBin
bl affichageMess
ldr x0,qAdrsZoneBin
bl affichageMess
ldr x0,qAdrszRetourLigne
bl affichageMess
/* other number */
mov x5,-1
mov x0,x5
ldr x1,qAdrsZoneConv
bl conversion10S
mov x0,x5
ldr x1,qAdrsZoneBin
bl conversion2 // binary conversion and display résult
ldr x0,qAdrsZoneBin
ldr x0,qAdrsMessAffBindeb
bl affichageMess
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrsMessAffBin
bl affichageMess
ldr x0,qAdrsZoneBin
bl affichageMess
ldr x0,qAdrszRetourLigne
bl affichageMess
/* other number */
mov x5,1
mov x0,x5
ldr x1,qAdrsZoneConv
bl conversion10S
mov x0,x5
ldr x1,qAdrsZoneBin
bl conversion2 // binary conversion and display résult
ldr x0,qAdrsZoneBin
ldr x0,qAdrsMessAffBindeb
bl affichageMess
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrsMessAffBin
bl affichageMess
ldr x0,qAdrsZoneBin
bl affichageMess
ldr x0,qAdrszRetourLigne
bl affichageMess
100: // standard end of the program */
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrsZoneBin: .quad sZoneBin
qAdrsMessAffBin: .quad sMessAffBin
qAdrsMessAffBindeb: .quad sMessAffBindeb
qAdrszRetourLigne: .quad szRetourLigne
/******************************************************************/
/* register conversion in binary */
/******************************************************************/
/* x0 contains the register */
/* x1 contains the address of receipt area */
conversion2:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
clz x2,x0 // number of left zeros bits
mov x3,64
sub x2,x3,x2 // number of significant bits
strb wzr,[x1,x2] // store 0 final
sub x3,x2,1 // position counter of the written character
2: // loop
tst x0,1 // test first bit
lsr x0,x0,#1 // shift right one bit
bne 3f
mov x4,#48 // bit = 0 => character '0'
b 4f
3:
mov x4,#49 // bit = 1 => character '1'
4:
strb w4,[x1,x3] // character in reception area at position counter
sub x3,x3,#1
subs x2,x2,#1 // 0 bits ?
bgt 2b // no! loop
100:
ldp x3,x4,[sp],16 // restaur 2 registres
ldp x2,lr,[sp],16 // restaur 2 registres
ret // retour adresse lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
- Output:
The decimal value +5 should produce an output of 101 The decimal value +50 should produce an output of 110010 The decimal value -1 should produce an output of 1111111111111111111111111111111111111111111111111111111111111111 The decimal value +1 should produce an output of 1
ACL2
(include-book "arithmetic-3/top" :dir :system)
(defun bin-string-r (x)
(if (zp x)
""
(string-append
(bin-string-r (floor x 2))
(if (= 1 (mod x 2))
"1"
"0"))))
(defun bin-string (x)
(if (zp x)
"0"
(bin-string-r x)))
Action!
PROC PrintBinary(CARD v)
CHAR ARRAY a(16)
BYTE i=[0]
DO
a(i)=(v&1)+'0
i==+1
v=v RSH 1
UNTIL v=0
OD
DO
i==-1
Put(a(i))
UNTIL i=0
OD
RETURN
PROC Main()
CARD ARRAY data=[0 5 50 9000]
BYTE i
CARD v
FOR i=0 TO 3
DO
v=data(i)
PrintF("Output for %I is ",v)
PrintBinary(v)
PutE()
OD
RETURN
- Output:
Screenshot from Atari 8-bit computer
Output for 0 is 0 Output for 5 is 101 Output for 50 is 110010 Output for 9000 is 10001100101000
Ada
with ada.text_io; use ada.text_io;
procedure binary is
bit : array (0..1) of character := ('0','1');
function bin_image (n : Natural) return string is
(if n < 2 then (1 => bit (n)) else bin_image (n / 2) & bit (n mod 2));
test_values : array (1..3) of Natural := (5,50,9000);
begin
for test of test_values loop
put_line ("Output for" & test'img & " is " & bin_image (test));
end loop;
end binary;
- Output:
Output for 5 is 101 Output for 50 is 110010 Output for 9000 is 10001100101000
Aime
o_xinteger(2, 0);
o_byte('\n');
o_xinteger(2, 5);
o_byte('\n');
o_xinteger(2, 50);
o_byte('\n');
o_form("/x2/\n", 9000);
- Output:
0 101 110010 10001100101000
ALGOL 68
File: Binary_digits.a68
#!/usr/local/bin/a68g --script #
printf((
$g" => "2r3d l$, 5, BIN 5,
$g" => "2r6d l$, 50, BIN 50,
$g" => "2r14d l$, 9000, BIN 9000
));
# or coerce to an array of BOOL #
print((
5, " => ", []BOOL(BIN 5)[bits width-3+1:], new line,
50, " => ", []BOOL(BIN 50)[bits width-6+1:], new line,
9000, " => ", []BOOL(BIN 9000)[bits width-14+1:], new line
))
- Output:
+5 => 101 +50 => 110010 +9000 => 10001100101000 +5 => TFT +50 => TTFFTF +9000 => TFFFTTFFTFTFFF
ALGOL W
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.
ALGOL-M
begin
procedure writebin(n);
integer n;
begin
procedure inner(x);
integer x;
begin
if x>1 then inner(x/2);
writeon(if x-x/2*2=0 then "0" else "1");
end;
write(""); % start new line %
inner(n);
end;
writebin(5);
writebin(50);
writebin(9000);
end
- Output:
101 110010 10001100101000
APL
Works in: Dyalog APL
A builtin function. Produces a boolean array.
base2←2∘⊥⍣¯1
Works in: GNU APL
Produces a boolean array.
base2 ← {((⌈2⍟⍵+1)⍴2)⊤⍵}
NOTE: Both versions above will yield an empty boolean array for 0.
base2 0 base2 5 1 0 1 base2 50 1 1 0 0 1 0 base2 9000 1 0 0 0 1 1 0 0 1 0 1 0 0 0
AppleScript
Functional
(ES6 version)
(The generic showIntAtBase here, which allows us to specify the digit set used (e.g. upper or lower case in hex, or different regional or other digit sets generally), is a rough translation of Haskell's Numeric.showintAtBase)
---------------------- BINARY STRING -----------------------
-- showBin :: Int -> String
on showBin(n)
script binaryChar
on |λ|(n)
text item (n + 1) of "01"
end |λ|
end script
showIntAtBase(2, binaryChar, n, "")
end showBin
--------------------------- TEST ---------------------------
on run
script
on |λ|(n)
intercalate(" -> ", {n as string, showBin(n)})
end |λ|
end script
return unlines(map(result, {5, 50, 9000}))
end run
-------------------- GENERIC FUNCTIONS ---------------------
-- showIntAtBase :: Int -> (Int -> Char) -> Int -> String -> String
on showIntAtBase(base, toChr, n, rs)
script showIt
on |λ|(nd_, r)
set {n, d} to nd_
set r_ to toChr's |λ|(d) & r
if n > 0 then
|λ|(quotRem(n, base), r_)
else
r_
end if
end |λ|
end script
if base ≤ 1 then
"error: showIntAtBase applied to unsupported base: " & base as string
else if n < 0 then
"error: showIntAtBase applied to negative number: " & base as string
else
showIt's |λ|(quotRem(n, base), rs)
end if
end showIntAtBase
-- quotRem :: Integral a => a -> a -> (a, a)
on quotRem(m, n)
{m div n, m mod n}
end quotRem
-------------------- GENERICS FOR TEST ---------------------
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- unlines :: [String] -> String
on unlines(xs)
intercalate(linefeed, xs)
end unlines
5 -> 101 50 -> 110010 9000 -> 10001100101000
Or using:
-- showBin :: Int -> String
on showBin(n)
script binaryChar
on |λ|(n)
text item (n + 1) of "〇一"
end |λ|
end script
showIntAtBase(2, binaryChar, n, "")
end showBin
- Output:
5 -> 一〇一 50 -> 一一〇〇一〇 9000 -> 一〇〇〇一一〇〇一〇一〇〇〇
Straightforward
At its very simplest, an AppleScript solution would look something like this:
on intToBinary(n)
set binary to (n mod 2 div 1) as text
set n to n div 2
repeat while (n > 0)
set binary to ((n mod 2 div 1) as text) & binary
set n to n div 2
end repeat
return binary
end intToBinary
display dialog ¬
intToBinary(5) & linefeed & ¬
intToBinary(50) & linefeed & ¬
intToBinary(9000) & linefeed
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:
on intToBinary(n)
set binary to ""
repeat
-- Calculate an integer value whose 8 decimal digits are the same as the low 8 binary digits of n's current value.
set binAsDec to (n div 128 mod 2 * 10000000 + n div 64 mod 2 * 1000000 + n div 32 mod 2 * 100000 + ¬
n div 16 mod 2 * 10000 + n div 8 mod 2 * 1000 + n div 4 mod 2 * 100 + n div 2 mod 2 * 10 + n mod 2) div 1
-- Coerce to text as appropriate, prepend to the output text, and prepare to get another 8 digits or not as necessary.
if (n > 255) then
set binary to text 2 thru -1 of ((100000000 + binAsDec) as text) & binary
set n to n div 256
else
set binary to (binAsDec as text) & binary
exit repeat
end if
end repeat
return binary
end intToBinary
display dialog ¬
intToBinary(5) & linefeed & ¬
intToBinary(50) & linefeed & ¬
intToBinary(9000) & linefeed
ARM Assembly
/* ARM assembly Raspberry PI */
/* program binarydigit.s */
/* Constantes */
.equ STDOUT, 1
.equ WRITE, 4
.equ EXIT, 1
/* Initialized data */
.data
sMessAffBin: .ascii "The decimal value "
sZoneDec: .space 12,' '
.ascii " should produce an output of "
sZoneBin: .space 36,' '
.asciz "\n"
/* code section */
.text
.global main
main: /* entry of program */
push {fp,lr} /* save des 2 registres */
mov r0,#5
ldr r1,iAdrsZoneDec
bl conversion10S @ decimal conversion
bl conversion2 @ binary conversion and display résult
mov r0,#50
ldr r1,iAdrsZoneDec
bl conversion10S
bl conversion2
mov r0,#-1
ldr r1,iAdrsZoneDec
bl conversion10S
bl conversion2
mov r0,#1
ldr r1,iAdrsZoneDec
bl conversion10S
bl conversion2
100: /* standard end of the program */
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrsZoneDec: .int sZoneDec
/******************************************************************/
/* register conversion in binary */
/******************************************************************/
/* r0 contains the register */
conversion2:
push {r0,lr} /* save registers */
push {r1-r5} /* save others registers */
ldr r1,iAdrsZoneBin @ address reception area
clz r2,r0 @ number of left zeros bits
rsb r2,#32 @ number of significant bits
mov r4,#' ' @ space
add r3,r2,#1 @ position counter in reception area
1:
strb r4,[r1,r3] @ space in other location of reception area
add r3,#1
cmp r3,#32 @ end of area ?
ble 1b @ no! loop
mov r3,r2 @ position counter of the written character
2: @ loop
lsrs r0,#1 @ shift right one bit with flags
movcc r4,#48 @ carry clear => character 0
movcs r4,#49 @ carry set => character 1
strb r4,[r1,r3] @ character in reception area at position counter
sub r3,r3,#1 @
subs r2,r2,#1 @ 0 bits ?
bgt 2b @ no! loop
ldr r0,iAdrsZoneMessBin
bl affichageMess
100:
pop {r1-r5} /* restaur others registers */
pop {r0,lr}
bx lr
iAdrsZoneBin: .int sZoneBin
iAdrsZoneMessBin: .int sMessAffBin
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {fp,lr} /* save registres */
push {r0,r1,r2,r7} /* save others registres */
mov r2,#0 /* counter length */
1: /* loop length calculation */
ldrb r1,[r0,r2] /* read octet start position + index */
cmp r1,#0 /* if 0 its over */
addne r2,r2,#1 /* else add 1 in the length */
bne 1b /* and loop */
/* so here r2 contains the length of the message */
mov r1,r0 /* address message in r1 */
mov r0,#STDOUT /* code to write to the standard output Linux */
mov r7, #WRITE /* code call system "write" */
swi #0 /* call systeme */
pop {r0,r1,r2,r7} /* restaur others registres */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* return */
/***************************************************/
/* conversion registre en décimal signé */
/***************************************************/
/* r0 contient le registre */
/* r1 contient l adresse de la zone de conversion */
conversion10S:
push {fp,lr} /* save des 2 registres frame et retour */
push {r0-r5} /* save autres registres */
mov r2,r1 /* debut zone stockage */
mov r5,#'+' /* par defaut le signe est + */
cmp r0,#0 /* nombre négatif ? */
movlt r5,#'-' /* oui le signe est - */
mvnlt r0,r0 /* et inversion en valeur positive */
addlt r0,#1
mov r4,#10 /* longueur de la zone */
1: /* debut de boucle de conversion */
bl divisionpar10 /* division */
add r1,#48 /* ajout de 48 au reste pour conversion ascii */
strb r1,[r2,r4] /* stockage du byte en début de zone r5 + la position r4 */
sub r4,r4,#1 /* position précedente */
cmp r0,#0
bne 1b /* boucle si quotient different de zéro */
strb r5,[r2,r4] /* stockage du signe à la position courante */
subs r4,r4,#1 /* position précedente */
blt 100f /* si r4 < 0 fin */
/* sinon il faut completer le debut de la zone avec des blancs */
mov r3,#' ' /* caractere espace */
2:
strb r3,[r2,r4] /* stockage du byte */
subs r4,r4,#1 /* position précedente */
bge 2b /* boucle si r4 plus grand ou egal a zero */
100: /* fin standard de la fonction */
pop {r0-r5} /*restaur des autres registres */
pop {fp,lr} /* restaur des 2 registres frame et retour */
bx lr
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 contient le dividende */
/* r0 retourne le quotient */
/* r1 retourne le reste */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} /* save others registers */
mov r4,r0
ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */
smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */
mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */
mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */
add r0, r2, r1 /* r0 <- r2 + r1 */
add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */
sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */
pop {r2-r4}
bx lr /* leave function */
.align 4
.Ls_magic_number_10: .word 0x66666667
Arturo
print as.binary 5
print as.binary 50
print as.binary 9000
- Output:
101 110010 10001100101000
AutoHotkey
MsgBox % NumberToBinary(5) ;101
MsgBox % NumberToBinary(50) ;110010
MsgBox % NumberToBinary(9000) ;10001100101000
NumberToBinary(InputNumber)
{
While, InputNumber
Result := (InputNumber & 1) . Result, InputNumber >>= 1
Return, Result
}
AutoIt
ConsoleWrite(IntToBin(50) & @CRLF)
Func IntToBin($iInt)
$Stack = ObjCreate("System.Collections.Stack")
Local $b = -1, $r = ""
While $iInt <> 0
$b = Mod($iInt, 2)
$iInt = INT($iInt/2)
$Stack.Push ($b)
WEnd
For $i = 1 TO $Stack.Count
$r &= $Stack.Pop
Next
Return $r
EndFunc ;==>IntToBin
AWK
BEGIN {
print tobinary(0)
print tobinary(1)
print tobinary(5)
print tobinary(50)
print tobinary(9000)
}
function tobinary(num) {
outstr = num % 2
while (num = int(num / 2))
outstr = (num % 2) outstr
return outstr
}
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.
Lbl BIN
.Axe supports 16-bit integers, so 16 digits are enough
L₁+16→P
0→{P}
While r₁
P--
{(r₁ and 1)▶Hex+3}→P
r₁/2→r₁
End
Disp P,i
Return
BaCon
' Binary digits
OPTION MEMTYPE int
INPUT n$
IF VAL(n$) = 0 THEN
PRINT "0"
ELSE
PRINT CHOP$(BIN$(VAL(n$)), "0", 1)
ENDIF
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
- Output:
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
BASIC
Applesoft BASIC
0 N = 5: GOSUB 1:N = 50: GOSUB 1:N = 9000: GOSUB 1: END
1 LET N2 = ABS ( INT (N))
2 LET B$ = ""
3 FOR N1 = N2 TO 0 STEP 0
4 LET N2 = INT (N1 / 2)
5 LET B$ = STR$ (N1 - N2 * 2) + B$
6 LET N1 = N2
7 NEXT N1
8 PRINT B$
9 RETURN
- Output:
101 110010 10001100101000
BASIC256
# DecToBin.bas
# BASIC256 1.1.4.0
dim a(3) #dimension a 3 element array (a)
a = {5, 50, 9000}
for i = 0 to 2
print a[i] + chr(9) + toRadix(a[i],2) # radix (decimal, base2)
next i
- Output:
5 101 50 110010 9000 10001100101000
BBC BASIC
FOR num% = 0 TO 16
PRINT FN_tobase(num%, 2, 0)
NEXT
END
REM Convert N% to string in base B% with minimum M% digits:
DEF FN_tobase(N%,B%,M%)
LOCAL D%,A$
REPEAT
D% = N%MODB%
N% DIV= B%
IF D%<0 D% += B%:N% -= 1
A$ = CHR$(48 + D% - 7*(D%>9)) + A$
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(5)
PRINT FNbinary(50)
PRINT FNbinary(9000)
END
DEF FNbinary(N%)
LOCAL A$
REPEAT
A$ = STR$(N% AND 1) + A$
N% = N% >>> 1 : REM BBC Basic prior to V5 can use N% = N% DIV 2
UNTIL N% = 0
=A$
CBASIC
rem - Return binary representation of n as a string
def fn.bin$(n%)
s$ = ""
while n% > 0
if (n% - (n% / 2) * 2) = 0 then \
s$ = "0" + s$ \
else \
s$ = "1" + s$
n% = n% / 2
wend
fn.bin$ = s$
return
fend
rem - exercise the function
print "5 = "; fn.bin$(5)
print "50 = "; fn.bin$(50)
print "9000 = "; fn.bin$(9000)
end
- Output:
5 = 101 50 = 110010 9000 = 10001100101000
Chipmunk Basic
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
Commodore BASIC
Since the task only requires nonnegative integers, we use a negative one to signal the end of the demonstration data.
Note the FOR N1 = ... TO 0 STEP 0 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 N1 to 0 so that the loop terminates – like a C for 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 while loops (DO WHILE ... LOOP was added in BASIC 3.5). The alternative would be a GOTO, but the FOR loop lends more structure.
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
- Output:
5 -> 101 50 -> 110010 9000 -> 10001100101000
IS-BASIC
10 PRINT BIN$(50)
100 DEF BIN$(N)
110 LET N=ABS(INT(N)):LET B$=""
120 DO
140 LET B$=STR$(MOD(N,2))&B$:LET N=INT(N/2)
150 LOOP WHILE N>0
160 LET BIN$=B$
170 END DEF
QBasic
FUNCTION BIN$ (N)
N = ABS(INT(N))
B$ = ""
DO
B$ = STR$(N MOD 2) + B$
N = INT(N / 2)
LOOP WHILE N > 0
BIN$ = B$
END FUNCTION
fmt$ = "#### -> &"
PRINT USING fmt$; 5; BIN$(5)
PRINT USING fmt$; 50; BIN$(50)
PRINT USING fmt$; 9000; BIN$(9000)
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 variables:
REM A-O: binary digits with A least significant and N most significant
REM X: number whose binary expansion we want
REM Z: running value
INPUT X
LET Z = X
IF Z = 0 THEN GOTO 999
IF (Z/2)*2<>Z THEN LET A = 1
LET Z = (Z - A) / 2
IF (Z/2)*2<>Z THEN LET B = 1
LET Z = (Z - B) / 2
IF (Z/2)*2<>Z THEN LET C = 1
LET Z = (Z - C) / 2
IF (Z/2)*2<>Z THEN LET D = 1
LET Z = (Z - D) / 2
IF (Z/2)*2<>Z THEN LET E = 1
LET Z = (Z - E) / 2
IF (Z/2)*2<>Z THEN LET F = 1
LET Z = (Z - F) / 2
IF (Z/2)*2<>Z THEN LET G = 1
LET Z = (Z - G) / 2
IF (Z/2)*2<>Z THEN LET H = 1 REM THIS IS ALL VERY TEDIOUS
LET Z = (Z - H) / 2
IF (Z/2)*2<>Z THEN LET I = 1
LET Z = (Z - I) / 2
IF (Z/2)*2<>Z THEN LET J = 1
LET Z = (Z - J) / 2
IF (Z/2)*2<>Z THEN LET K = 1
LET Z = (Z - K) / 2
IF (Z/2)*2<>Z THEN LET L = 1
LET Z = (Z - L) / 2
IF (Z/2)*2<>Z THEN LET M = 1
LET Z = (Z - M) / 2
IF (Z/2)*2<>Z THEN LET N = 1
LET Z = (Z - N) / 2
LET O = Z
IF X >= 16384 THEN GOTO 114
IF X >= 8192 THEN GOTO 113
IF X >= 4096 THEN GOTO 112
IF X >= 2048 THEN GOTO 111
IF X >= 1024 THEN GOTO 110
IF X >= 512 THEN GOTO 109
IF X >= 256 THEN GOTO 108
IF X >= 128 THEN GOTO 107 REM THIS IS ALSO TEDIOUS
IF X >= 64 THEN GOTO 106
IF X >= 32 THEN GOTO 105
IF X >= 16 THEN GOTO 104
IF X >= 8 THEN GOTO 103
IF X >= 4 THEN GOTO 102
IF X >= 2 THEN GOTO 101
PRINT 1
END
101 PRINT B,A
END
102 PRINT C,B,A
END
103 PRINT D,C,B,A
END
104 PRINT E,D,C,B,A
END
105 PRINT F,E,D,C,B,A
END
106 PRINT G,F,E,D,C,B,A
END
107 PRINT H,G,F,E,D,C,B,A
END
108 PRINT I,H,G,D,E,D,C,B,A
END
109 PRINT J,I,H,G,F,E,D,C,B,A
END
110 PRINT K,J,I,H,G,F,E,D,C,B,A
END
111 PRINT L,K,J,I,H,G,D,E,D,C,B,A
END
112 PRINT M,L,K,J,I,H,G,F,E,D,C,B,A
END
113 PRINT N,M,L,K,J,I,H,G,F,E,D,C,B,A
END
114 PRINT O,N,M,L,K,J,I,H,G,F,E,D,C,B,A
END
999 PRINT 0 REM zero is the one time we DO want to print a leading zero
END
True BASIC
FUNCTION BIN$ (N)
LET N = ABS(INT(N))
LET B$ = ""
DO
LET I = MOD(N, 2)
LET B$ = STR$(I) & B$
LET N = INT(N / 2)
LOOP WHILE N > 0
LET BIN$ = B$
END FUNCTION
PRINT USING "####": 5;
PRINT " -> "; BIN$(5)
PRINT USING "####": 50;
PRINT " -> "; BIN$(50)
PRINT USING "####": 9000;
PRINT " -> "; BIN$(9000)
END
XBasic
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
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.
@echo off
:num2bin IntVal [RtnVar]
setlocal enableDelayedExpansion
set /a n=%~1
set rtn=
for /l %%b in (0,1,31) do (
set /a "d=n&1, n>>=1"
set rtn=!d!!rtn!
)
for /f "tokens=* delims=0" %%a in ("!rtn!") do set rtn=%%a
(endlocal & rem -- return values
if "%~2" neq "" (set %~2=%rtn%) else echo %rtn%
)
exit /b
bc
obase = 2
5
50
9000
quit
BCPL
get "libhdr"
let writebin(x) be
$( let f(x) be
$( if x>1 then f(x>>1)
wrch((x & 1) + '0')
$)
f(x)
wrch('*N')
$)
let start() be
$( writebin(5)
writebin(50)
writebin(9000)
$)
- Output:
101 110010 10001100101000
Beads
beads 1 program 'Binary Digits'
calc main_init
loop across:[5, 50, 9000] val:v
log to_str(v, base:2)
- Output:
101 110010 10001100101000
Befunge
Reads the number to convert from standard input.
&>0\55+\:2%68>*#<+#8\#62#%/#2:_$>:#,_$@
- Output:
9000 10001100101000
BQN
A BQNcrate idiom which returns the digits as a boolean array.
Bin ← 2{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}
Bin¨5‿50‿9000
⟨ ⟨ 1 0 1 ⟩ ⟨ 1 1 0 0 1 0 ⟩ ⟨ 1 0 0 0 1 1 0 0 1 0 1 0 0 0 ⟩ ⟩
Bracmat
( dec2bin
= bit bits
. :?bits
& whl
' ( !arg:>0
& mod$(!arg,2):?bit
& div$(!arg,2):?arg
& !bit !bits:?bits
)
& (str$!bits:~|0)
)
& 0 5 50 9000 423785674235000123456789:?numbers
& whl
' ( !numbers:%?dec ?numbers
& put$(str$(!dec ":\n" dec2bin$!dec \n\n))
)
;
- Output:
0: 0 5: 101 50: 110010 9000: 10001100101000 423785674235000123456789: 1011001101111010111011110101001101111000000000000110001100000100111110100010101
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.
+[ Start with n=1 to kick off the loop
[>>++<< Set up {n 0 2} for divmod magic
[->+>- Then
[>+>>]> do
[+[-<+>]>+>>] the
<<<<<<] magic
>>>+ Increment n % 2 so that 0s don't break things
>] Move into n / 2 and divmod that unless it's 0
-< Set up sentinel ‑1 then move into the first binary digit
[++++++++ ++++++++ ++++++++ Add 47 to get it to ASCII
++++++++ ++++++++ +++++++. and print it
[<]<] Get to a 0; the cell to the left is the next binary digit
>>[<+>-] Tape is {0 n}; make it {n 0}
>[>+] Get to the ‑1
<[[-]<] Zero the tape for the next iteration
++++++++++. Print a newline
[-]<+] Zero it then increment n and go again
Burlesque
blsq ) {5 50 9000}{2B!}m[uN
101
110010
10001100101000
C
With bit level operations
#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings
#define _CRT_NONSTDC_NO_DEPRECATE // enable old-gold POSIX names in MSVS
#include <stdio.h>
#include <stdlib.h>
char* bin2str(unsigned value, char* buffer)
{
// This algorithm is not the fastest one, but is relativelly simple.
//
// A faster algorithm would be conversion octets to strings by a lookup table.
// There is only 2**8 == 256 octets, therefore we would need only 2048 bytes
// for the lookup table. Conversion of a 64-bit integers would need 8 lookups
// instead 64 and/or/shifts of bits etc. Even more... lookups may be implemented
// with XLAT or similar CPU instruction... and AVX/SSE gives chance for SIMD.
const unsigned N_DIGITS = sizeof(unsigned) * 8;
unsigned mask = 1 << (N_DIGITS - 1);
char* ptr = buffer;
for (int i = 0; i < N_DIGITS; i++)
{
*ptr++ = '0' + !!(value & mask);
mask >>= 1;
}
*ptr = '\0';
// Remove leading zeros.
//
for (ptr = buffer; *ptr == '0'; ptr++)
;
return ptr;
}
char* bin2strNaive(unsigned value, char* buffer)
{
// This variation of the solution doesn't use bits shifting etc.
unsigned n, m, p;
n = 0;
p = 1; // p = 2 ** n
while (p <= value / 2)
{
n = n + 1;
p = p * 2;
}
m = 0;
while (n > 0)
{
buffer[m] = '0' + value / p;
value = value % p;
m = m + 1;
n = n - 1;
p = p / 2;
}
buffer[m + 1] = '\0';
return buffer;
}
int main(int argc, char* argv[])
{
const unsigned NUMBERS[] = { 5, 50, 9000 };
const int RADIX = 2;
char buffer[(sizeof(unsigned)*8 + 1)];
// Function itoa is an POSIX function, but it is not in C standard library.
// There is no big surprise that Microsoft deprecate itoa because POSIX is
// "Portable Operating System Interface for UNIX". Thus it is not a good
// idea to use _itoa instead itoa: we lost compatibility with POSIX;
// we gain nothing in MS Windows (itoa-without-underscore is not better
// than _itoa-with-underscore). The same holds for kbhit() and _kbhit() etc.
//
for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++)
{
unsigned value = NUMBERS[i];
itoa(value, buffer, RADIX);
printf("itoa: %u decimal = %s binary\n", value, buffer);
}
// Yeep, we can use a homemade bin2str function. Notice that C is very very
// efficient (as "hi level assembler") when bit manipulation is needed.
//
for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++)
{
unsigned value = NUMBERS[i];
printf("bin2str: %u decimal = %s binary\n", value, bin2str(value, buffer));
}
// Another implementation - see above.
//
for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++)
{
unsigned value = NUMBERS[i];
printf("bin2strNaive: %u decimal = %s binary\n", value, bin2strNaive(value, buffer));
}
return EXIT_SUCCESS;
}
- Output:
itoa: 5 decimal = 101 binary itoa: 50 decimal = 110010 binary itoa: 9000 decimal = 10001100101000 binary bin2str: 5 decimal = 101 binary bin2str: 50 decimal = 110010 binary bin2str: 9000 decimal = 10001100101000 binary bin2strNaive: 5 decimal = 101 binary bin2strNaive: 50 decimal = 110010 binary bin2strNaive: 9000 decimal = 10001100101000 binary
With malloc and log10
Converts int to a string.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
char *bin(uint32_t x);
int main(void)
{
for (size_t i = 0; i < 20; i++) {
char *binstr = bin(i);
printf("%s\n", binstr);
free(binstr);
}
}
char *bin(uint32_t x)
{
size_t bits = (x == 0) ? 1 : log10((double) x)/log10(2) + 1;
char *ret = malloc((bits + 1) * sizeof (char));
for (size_t i = 0; i < bits ; i++) {
ret[bits - i - 1] = (x & 1) ? '1' : '0';
x >>= 1;
}
ret[bits] = '\0';
return ret;
}
- Output:
0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 10000 10001 10010 10011
C#
using System;
class Program
{
static void Main()
{
foreach (var number in new[] { 5, 50, 9000 })
{
Console.WriteLine(Convert.ToString(number, 2));
}
}
}
Another version using dotnet 5
using System;
using System.Text;
static string ToBinary(uint x) {
if(x == 0) return "0";
var bin = new StringBuilder();
for(uint mask = (uint)1 << (sizeof(uint)*8 - 1);mask > 0;mask = mask >> 1)
bin.Append((mask & x) > 0 ? "1" : "0");
return bin.ToString().TrimStart('0');
}
Console.WriteLine(ToBinary(5));
Console.WriteLine(ToBinary(50));
Console.WriteLine(ToBinary(9000));
- Output:
101 110010 10001100101000
C++
#include <bitset>
#include <iostream>
#include <limits>
#include <string>
void print_bin(unsigned int n) {
std::string str = "0";
if (n > 0) {
str = std::bitset<std::numeric_limits<unsigned int>::digits>(n).to_string();
str = str.substr(str.find('1')); // remove leading zeros
}
std::cout << str << '\n';
}
int main() {
print_bin(0);
print_bin(5);
print_bin(50);
print_bin(9000);
}
- Output:
0 101 110010 10001100101000
Shorter version using bitset
#include <iostream>
#include <bitset>
void printBits(int n) { // Use int like most programming languages.
int iExp = 0; // Bit-length
while (n >> iExp) ++iExp; // Could use template <log(x)*1.44269504088896340736>
for (int at = iExp - 1; at >= 0; at--) // Reverse iter from the bit-length to 0 - msb is at end
std::cout << std::bitset<32>(n)[at]; // Show 1's, show lsb, hide leading zeros
std::cout << '\n';
}
int main(int argc, char* argv[]) {
printBits(5);
printBits(50);
printBits(9000);
} // for testing with n=0 printBits<32>(0);
Using >> operator. (1st example is 2.75x longer. Matter of taste.)
#include <iostream>
int main(int argc, char* argv[]) {
unsigned int in[] = {5, 50, 9000}; // Use int like most programming languages
for (int i = 0; i < 3; i++) // Use all inputs
for (int at = 31; at >= 0; at--) // reverse iteration from the max bit-length to 0, because msb is at the end
if (int b = (in[i] >> at)) // skip leading zeros. Start output when significant bits are set
std::cout << ('0' + b & 1) << (!at ? "\n": ""); // '0' or '1'. Add EOL if last bit of num
}
To be fair comparison with languages that doesn't declare a function like C++ main(). 3.14x shorter than 1st example.
#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
for (int at = 31; at >= 0; at--) // reverse iteration from the max bit-length to 0, because msb is at the end
if (int b = (atoi(argv[i]) >> at)) // skip leading zeros
std::cout << ('0' + b & 1) << (!at ? "\n": ""); // '0' or '1'. Add EOL if last bit of num
}
Using bitwise operations with recursion.
#include <iostream>
std::string binary(int n) {
return n == 0 ? "" : binary(n >> 1) + std::to_string(n & 1);
}
int main(int argc, char* argv[]) {
for (int i = 1; i < argc; ++i) {
std::cout << binary(std::stoi(argv[i])) << std::endl;
}
}
- Output:
101 110010 10001100101000
Ceylon
shared void run() {
void printBinary(Integer integer) =>
print(Integer.format(integer, 2));
printBinary(5);
printBinary(50);
printBinary(9k);
}
Clojure
(Integer/toBinaryString 5)
(Integer/toBinaryString 50)
(Integer/toBinaryString 9000)
CLU
binary = proc (n: int) returns (string)
bin: string := ""
while n > 0 do
bin := string$c2s(char$i2c(48 + n // 2)) || bin
n := n / 2
end
return(bin)
end binary
start_up = proc ()
po: stream := stream$primary_output()
tests: array[int] := array[int]$[5, 50, 9000]
for test: int in array[int]$elements(tests) do
stream$putl(po, int$unparse(test) || " -> " || binary(test))
end
end start_up
- Output:
5 -> 101 50 -> 110010 9000 -> 10001100101000
COBOL
IDENTIFICATION DIVISION.
PROGRAM-ID. SAMPLE.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 binary_number pic X(21).
01 str pic X(21).
01 binary_digit pic X.
01 digit pic 9.
01 n pic 9(7).
01 nstr pic X(7).
PROCEDURE DIVISION.
accept nstr
move nstr to n
perform until n equal 0
divide n by 2 giving n remainder digit
move digit to binary_digit
string binary_digit DELIMITED BY SIZE
binary_number DELIMITED BY SPACE
into str
move str to binary_number
end-perform.
display binary_number
stop run.
Free-form, using a reference modifier to index into binary-number.
IDENTIFICATION DIVISION.
PROGRAM-ID. binary-conversion.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 binary-number pic X(21).
01 digit pic 9.
01 n pic 9(7).
01 nstr pic X(7).
01 ptr pic 99.
PROCEDURE DIVISION.
display "Number: " with no advancing.
accept nstr.
move nstr to n.
move zeroes to binary-number.
move length binary-number to ptr.
perform until n equal 0
divide n by 2 giving n remainder digit
move digit to binary-number(ptr:1)
subtract 1 from ptr
if ptr < 1
exit perform
end-if
end-perform.
display binary-number.
stop run.
CoffeeScript
binary = (n) ->
new Number(n).toString(2)
console.log binary n for n in [5, 50, 9000]
Common Lisp
Just print the number with "~b":
(format t "~b" 5)
; or
(write 5 :base 2)
Component Pascal
BlackBox Component Builder
MODULE BinaryDigits;
IMPORT StdLog,Strings;
PROCEDURE Do*;
VAR
str : ARRAY 33 OF CHAR;
BEGIN
Strings.IntToStringForm(5,2, 1,'0',FALSE,str);
StdLog.Int(5);StdLog.String(":> " + str);StdLog.Ln;
Strings.IntToStringForm(50,2, 1,'0',FALSE,str);
StdLog.Int(50);StdLog.String(":> " + str);StdLog.Ln;
Strings.IntToStringForm(9000,2, 1,'0',FALSE,str);
StdLog.Int(9000);StdLog.String(":> " + str);StdLog.Ln;
END Do;
END BinaryDigits.
Execute: ^Q BinaryDigits.Do
- Output:
5:> 101 50:> 110010 9000:> 10001100101000
Cowgol
include "cowgol.coh";
sub print_binary(n: uint32) is
var buffer: uint8[33];
var p := &buffer[32];
[p] := 0;
while n != 0 loop
p := @prev p;
[p] := ((n as uint8) & 1) + '0';
n := n >> 1;
end loop;
print(p);
print_nl();
end sub;
print_binary(5);
print_binary(50);
print_binary(9000);
- Output:
101 110010 10001100101000
Crystal
Using an array
[5,50,9000].each do |n|
puts "%b" % n
end
Using a tuple
{5,50,9000}.each { |n| puts n.to_s(2) }
- Output:
101 110010 10001100101000
D
void main() {
import std.stdio;
foreach (immutable i; 0 .. 16)
writefln("%b", i);
}
- Output:
0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111
Dart
String binary(int n) {
if(n<0)
throw new IllegalArgumentException("negative numbers require 2s complement");
if(n==0) return "0";
String res="";
while(n>0) {
res=(n%2).toString()+res;
n=(n/2).toInt();
}
return res;
}
main() {
print(binary(0));
print(binary(1));
print(binary(5));
print(binary(10));
print(binary(50));
print(binary(9000));
print(binary(65535));
print(binary(0xaa5511ff));
print(binary(0x123456789abcde));
// fails due to precision limit
print(binary(0x123456789abcdef));
}
dc
2o 5p 50p 9000p
- Output:
101 110010 10001100101000
Delphi
program BinaryDigit;
{$APPTYPE CONSOLE}
uses
sysutils;
function IntToBinStr(AInt : LongWord) : string;
begin
Result := '';
repeat
Result := Chr(Ord('0')+(AInt and 1))+Result;
AInt := AInt div 2;
until (AInt = 0);
end;
Begin
writeln(' 5: ',IntToBinStr(5));
writeln(' 50: ',IntToBinStr(50));
writeln('9000: '+IntToBinStr(9000));
end.
- Output:
5: 101 50: 110010 9000: 10001100101000
Draco
proc main() void:
writeln(5:b);
writeln(50:b);
writeln(9000:b);
corp
- Output:
101 110010 10001100101000
DuckDB
Using format()
SELECT n, format('{:b}', n)
FROM (select unnest(range(0, 6) || [50, 9000]) as n);
Apart from the headers, the output is identical to the corresponding table below and so is not repeated here.
Recursive CTE
# n is assumed to be a non-negative integer
CREATE OR REPLACE FUNCTION binary_digits(n) as (
WITH RECURSIVE cte(num, str) as (
-- Base case
SELECT n, ''
UNION ALL
-- Recursive case: divide by 2 and build the binary string
SELECT num // 2, (num % 2) || str
FROM cte
WHERE num > 0
)
SELECT CASE WHEN str = '' THEN '0' ELSE str END
FROM cte
WHERE num = 0
LIMIT 1
);
select n, binary_digits(n)
from (select unnest(range(0, 6) || [50, 9000]) as n);
.maxwidth 200
select n, binary_digits(n) from (select 123456789123456789123456789123456789 as n)
- Output:
┌───────┬──────────────────┐ │ n │ binary_digits(n) │ │ int64 │ varchar │ ├───────┼──────────────────┤ │ 0 │ 0 │ │ 1 │ 1 │ │ 2 │ 10 │ │ 3 │ 11 │ │ 4 │ 100 │ │ 5 │ 101 │ │ 50 │ 110010 │ │ 9000 │ 10001100101000 │ └───────┴──────────────────┘ ┌──────────────────────────────────────┬───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ │ n │ binary_digits(n) │ │ int128 │ varchar │ ├──────────────────────────────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ │ 123456789123456789123456789123456789 │ 101111100011011100011110000000011001011111000100100000100010110101101011101000110011010000100000001000101111100010101 │ └──────────────────────────────────────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
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
- Output:
0 1 10 101 110010 10001100101000
Dyalect
A default ToString
method of type Integer
is overridden and returns a binary representation of a number:
func Integer.ToString() {
var s = ""
for x in 31^-1..0 {
if this &&& (1 <<< x) != 0 {
s += "1"
} else if s != "" {
s += "0"
}
}
s
}
print("5 == \(5), 50 = \(50), 1000 = \(9000)")
- Output:
5 == 101, 50 = 110010, 1000 = 10001100101000
EasyLang
func$ bin num .
while num > 1
b$ = num mod 2 & b$
num = num div 2
.
return num & b$
.
print bin 5
print bin 50
print bin 9000
- Output:
101 110010 10001100101000
EchoLisp
;; primitive : (number->string number [base]) - default base = 10
(number->string 2 2)
→ 10
(for-each (compose writeln (rcurry number->string 2)) '( 5 50 9000)) →
101
110010
10001100101000
Ecstasy
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)}");
}
}
}
- Output:
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
ed
Supports up to 2^15, duplicate the
g/^\(i*\)\1i\([^i]\)/s//\11\2/
g/^\(i*\)\1\([^i]\)/s//\10\2/
part more.
# by Artyom Bologov
H
# decimal -> unary
g/[^0-9]\{1,\}/s///g
g/^0\{1,\}\([0-9]\)/s//\1/
g/^9\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiiii/
g/^8\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiii/
g/^7\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiii/
g/^6\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiii/
g/^5\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiii/
g/^4\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiii/
g/^3\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iii/
g/^2\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2ii/
g/^1\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2i/
g/^0\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2/
g/^9\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiiii/
g/^8\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiii/
g/^7\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiii/
g/^6\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiii/
g/^5\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiii/
g/^4\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiii/
g/^3\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iii/
g/^2\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2ii/
g/^1\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2i/
g/^0\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2/
g/^9\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiiii/
g/^8\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiii/
g/^7\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiii/
g/^6\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiii/
g/^5\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiii/
g/^4\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiii/
g/^3\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iii/
g/^2\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2ii/
g/^1\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2i/
g/^0\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2/
g/^9\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiiii/
g/^8\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiii/
g/^7\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiii/
g/^6\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiii/
g/^5\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiii/
g/^4\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiii/
g/^3\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iii/
g/^2\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2ii/
g/^1\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2i/
g/^0\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2/
g/^9\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiiii/
g/^8\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiii/
g/^7\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiii/
g/^6\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiii/
g/^5\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiiii/
g/^4\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iiii/
g/^3\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2iii/
g/^2\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2ii/
g/^1\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2i/
g/^0\([0-9]*\)\(i*\)/s//\1\2\2\2\2\2\2\2\2\2\2/
# actual logic
g/.*/s/$/0/
g/^\(i*\)\1i\([^i]\)/s//\11\2/
g/^\(i*\)\1\([^i]\)/s//\10\2/
g/^\(i*\)\1i\([^i]\)/s//\11\2/
g/^\(i*\)\1\([^i]\)/s//\10\2/
g/^\(i*\)\1i\([^i]\)/s//\11\2/
g/^\(i*\)\1\([^i]\)/s//\10\2/
g/^\(i*\)\1i\([^i]\)/s//\11\2/
g/^\(i*\)\1\([^i]\)/s//\10\2/
g/^\(i*\)\1i\([^i]\)/s//\11\2/
g/^\(i*\)\1\([^i]\)/s//\10\2/
g/^\(i*\)\1i\([^i]\)/s//\11\2/
g/^\(i*\)\1\([^i]\)/s//\10\2/
g/^\(i*\)\1i\([^i]\)/s//\11\2/
g/^\(i*\)\1\([^i]\)/s//\10\2/
g/^\(i*\)\1i\([^i]\)/s//\11\2/
g/^\(i*\)\1\([^i]\)/s//\10\2/
g/^\(i*\)\1i\([^i]\)/s//\11\2/
g/^\(i*\)\1\([^i]\)/s//\10\2/
g/^\(i*\)\1i\([^i]\)/s//\11\2/
g/^\(i*\)\1\([^i]\)/s//\10\2/
g/^\(i*\)\1i\([^i]\)/s//\11\2/
g/^\(i*\)\1\([^i]\)/s//\10\2/
g/^\(i*\)\1i\([^i]\)/s//\11\2/
g/^\(i*\)\1\([^i]\)/s//\10\2/
g/^\(i*\)\1i\([^i]\)/s//\11\2/
g/^\(i*\)\1\([^i]\)/s//\10\2/
g/^\(i*\)\1i\([^i]\)/s//\11\2/
g/^\(i*\)\1\([^i]\)/s//\10\2/
g/^\(i*\)\1i\([^i]\)/s//\11\2/
g/^\(i*\)\1\([^i]\)/s//\10\2/
g/^0*\(1.*\)0$/s//\1/
,p
Q
- Output:
$ ed -s 2binary.input < 2binary.ed Newline appended 101 110010 10001100101000
Elena
ELENA 6.x :
import system'routines;
import extensions;
public program()
{
new int[]{5,50,9000}.forEach::(n)
{
console.printLine(n.toString(2))
}
}
- Output:
101 110010 10001100101000
Elixir
Use Integer.to_string
with a base of 2:
IO.puts Integer.to_string(5, 2)
Or, using the pipe operator:
5 |> Integer.to_string(2) |> IO.puts
[5,50,9000] |> Enum.each(fn n -> IO.puts Integer.to_string(n, 2) end)
- Output:
101 110010 10001100101000
With Enum.map/2
Enum.map([5, 50, 9000], fn n -> IO.puts Integer.to_string(n, 2) end)
- Output:
101 110010 10001100101000
With list comprehension
for n <- [5, 50, 9000] do IO.puts Integer.to_string(n, 2) end
- Output:
101 110010 10001100101000
Emacs 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))
- Output:
5 => 101 50 => 110010 9000 => 10001100101000
Epoxy
fn bin(a,b:true)
var c:""
while a>0 do
c,a:tostring(a%2)+c,bit.rshift(a,1)
cls
if b then
c:string.repeat("0",16-#c)+c
cls
return c
cls
var List: [5,50,9000]
iter Value of List do
log(Value+": "+bin(Value,false))
cls
- Output:
5: 101 50: 110010 9000: 10001100101000
Erlang
With lists:map/2
lists:map( fun(N) -> io:fwrite("~.2B~n", [N]) end, [5, 50, 9000]).
- Output:
101 110010 10001100101000
With list comprehension
[io:fwrite("~.2B~n", [N]) || N <- [5, 50, 9000]].
- Output:
101 110010 10001100101000
With list comprehension and integer_to_list/2
[io:fwrite("~s~n", [integer_to_list(N, 2)]) || N <- [5, 50, 9000]].
- Output:
101 110010 10001100101000
Euphoria
function toBinary(integer i)
sequence s
s = {}
while i do
s = prepend(s, '0'+and_bits(i,1))
i = floor(i/2)
end while
return s
end function
puts(1, toBinary(5) & '\n')
puts(1, toBinary(50) & '\n')
puts(1, toBinary(9000) & '\n')
Functional/Recursive
include std/math.e
include std/convert.e
function Bin(integer n, sequence s = "")
if n > 0 then
return Bin(floor(n/2),(mod(n,2) + #30) & s)
end if
if length(s) = 0 then
return to_integer("0")
end if
return to_integer(s)
end function
printf(1, "%d\n", Bin(5))
printf(1, "%d\n", Bin(50))
printf(1, "%d\n", Bin(9000))
F#
By translating C#'s approach, using imperative coding style (inflexible):
open System
for i in [5; 50; 9000] do printfn "%s" <| Convert.ToString (i, 2)
Alternatively, by creating a function printBin
which prints in binary (more flexible):
open System
// define the function
let printBin (i: int) =
Convert.ToString (i, 2)
|> printfn "%s"
// 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 %a
format specifier (most flexible):
open System
open System.IO
// define a callback function for %a
let bin (tw: TextWriter) value =
tw.Write("{0}", Convert.ToString(int64 value, 2))
// use it with printfn with %a
[5; 50; 9000]
|> List.iter (printfn "binary: %a" bin)
Output (either version):
101 110010 10001100101000
Factor
USING: io kernel math math.parser ;
5 >bin print
50 >bin print
9000 >bin print
FALSE
[0\10\[$1&'0+\2/$][]#%[$][,]#%]b:
5 b;!
50 b;!
9000 b;!
- Output:
101 110010 10001100101000
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)
if s = "" then return "0"
return s
end function
print Bin(5)
print Bin(50)
print Bin(9000)
pause
FOCAL
01.10 S A=5;D 2
01.20 S A=50;D 2
01.30 S A=9000;D 2
01.40 Q
02.10 S BX=0
02.20 S BD(BX)=A-FITR(A/2)*2
02.25 S A=FITR(A/2)
02.30 S BX=BX+1
02.35 I (-A)2.2
02.40 S BX=BX-1
02.45 D 2.6
02.50 I (-BX)2.4;T !;R
02.60 I (-BD(BX))2.7;T "0";R
02.70 T "1"
- Output:
101 110010 10001100101000
Forth
\ Forth uses a system variable 'BASE' for number conversion
\ HEX is a standard word to change the value of base to 16
\ DECIMAL is a standard word to change the value of base to 10
\ we can easily compile a word into the system to set 'BASE' to 2
: binary 2 base ! ;
\ interactive console test with conversion and binary masking example
hex 0FF binary . cr
decimal 679 binary . cr
binary 11111111111 00000110000 and . cr
decimal
- Output:
11111111 1010100111 110000
Fortran
Please find compilation instructions and the example run at the start of the FORTRAN90 source that follows. Thank you.
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sun May 19 23:14:14
!
!a=./F && make $a && $a < unixdict.txt
!f95 -Wall -ffree-form F.F -o F
!101
!110010
!10001100101000
!
!Compilation finished at Sun May 19 23:14:14
!
!
! tobin=: -.&' '@":@#:
! tobin 5
!101
! tobin 50
!110010
! tobin 9000
!10001100101000
program bits
implicit none
integer, dimension(3) :: a
integer :: i
data a/5,50,9000/
do i = 1, 3
call s(a(i))
enddo
contains
subroutine s(a)
integer, intent(in) :: a
integer :: i
if (a .eq. 0) then
write(6,'(a)')'0'
return
endif
do i = 31, 0, -1
if (btest(a, i)) exit
enddo
do while (0 .lt. i)
if (btest(a, i)) then
write(6,'(a)',advance='no')'1'
else
write(6,'(a)',advance='no')'0'
endif
i = i-1
enddo
if (btest(a, i)) then
write(6,'(a)')'1'
else
write(6,'(a)')'0'
endif
end subroutine s
end program bits
Free Pascal
As part of the RTL (run-time library) that is shipped with every FPC (Free Pascal compiler) distribution, the system unit contains the function binStr. The system unit is automatically included by every program and is guaranteed to work on every supported platform.
program binaryDigits(input, output, stdErr);
{$mode ISO}
function binaryNumber(const value: nativeUInt): shortString;
const
one = '1';
var
representation: shortString;
begin
representation := binStr(value, bitSizeOf(value));
// strip leading zeroes, if any; NB: mod has to be ISO compliant
delete(representation, 1, (pos(one, representation)-1) mod bitSizeOf(value));
// traditional Pascal fashion:
// assign result to the (implicitely existent) variable
// that is named like the function’s name
binaryNumber := representation;
end;
begin
writeLn(binaryNumber(5));
writeLn(binaryNumber(50));
writeLn(binaryNumber(9000));
end.
Note, that the ISO compliant mod operation has to be used, which is ensured by the {$mode} directive in the second line.
FreeBASIC
' FreeBASIC v1.05.0 win64
Dim As String fmt = "#### -> &"
Print Using fmt; 5; Bin(5)
Print Using fmt; 50; Bin(50)
Print Using fmt; 9000; Bin(9000)
Print
Print "Press any key to exit the program"
Sleep
End
- Output:
5 -> 101 50 -> 110010 9000 -> 10001100101000
Frink
The following all provide equivalent output. Input can be arbitrarily-large integers.
9000 -> binary
9000 -> base2
base2[9000]
base[9000, 2]
FunL
for n <- [5, 50, 9000, 9000000000]
println( n, bin(n) )
- Output:
5, 101 50, 110010 9000, 10001100101000 9000000000, 1000011000011100010001101000000000
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.
fun main(x: i32): i64 =
loop (out = 0i64) = for i < 32 do
let digit = (x >> (31-i)) & 1
let out = (out * 10i64) + i64(digit)
in out
in out
FutureBasic
The decimal to binary conversion can be handled with a simple function.
include "NSLog.incl"
local fn IntegerToBinaryStr( x as NSInteger ) as CFStringRef
CFStringRef resultStr : resultStr = @""
while ( x )
resultStr = fn StringByAppendingString( fn StringWithFormat( @"%lu", x && 1 ), resultStr )
x = x >> 1
wend
end fn = resultStr
NSLog( @" 5 = %@", fn IntegerToBinaryStr( 5 ) )
NSLog( @" 50 = %@", fn IntegerToBinaryStr( 50 ) )
NSLog( @"9000 = %@", fn IntegerToBinaryStr( 9000 ) )
HandleEvents
- Output:
5 = 101 50 = 110010 9000 = 10001100101000
Gambas
Click this link to run this code
Public Sub Main()
Dim siBin As Short[] = [5, 50, 9000]
Dim siCount As Short
For siCount = 0 To siBin.Max
Print Bin(siBin[siCount])
Next
End
- Output:
101 110010 10001100101000
Go
package main
import (
"fmt"
)
func main() {
for i := 0; i < 16; i++ {
fmt.Printf("%b\n", i)
}
}
- Output:
0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111
Groovy
Solutions:
print '''
n binary
----- ---------------
'''
[5, 50, 9000].each {
printf('%5d %15s\n', it, Integer.toBinaryString(it))
}
- Output:
n binary ----- --------------- 5 101 50 110010 9000 10001100101000
Haskell
import Data.List
import Numeric
import Text.Printf
-- Use the built-in function showBin.
toBin n = showBin n ""
-- Use the built-in function showIntAtBase.
toBin n = showIntAtBase 2 ("01" !!) n ""
-- Implement our own version.
toBin1 0 = []
toBin1 x = (toBin1 $ x `div` 2) ++ (show $ x `mod` 2)
-- Or even more efficient (due to fusion) and universal implementation
toBin2 = foldMap show . reverse . toBase 2
toBase base = unfoldr modDiv
where modDiv 0 = Nothing
modDiv n = let (q, r) = (n `divMod` base) in Just (r, q)
printToBin n = putStrLn $ printf "%4d %14s %14s" n (toBin n) (toBin1 n)
main = do
putStrLn $ printf "%4s %14s %14s" "N" "toBin" "toBin1"
mapM_ printToBin [5, 50, 9000]
- Output:
N toBin toBin1 5 101 101 50 110010 110010 9000 10001100101000 10001100101000
and in terms of first and swap, we could also write this as:
import Data.Bifunctor (first)
import Data.List (unfoldr)
import Data.Tuple (swap)
---------------------- BINARY DIGITS ---------------------
binaryDigits :: Int -> String
binaryDigits = reverse . unfoldr go
where
go 0 = Nothing
go n = Just . first ("01" !!) . swap . quotRem n $ 2
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_
( putStrLn
. ( ((<>) . (<> " -> ") . show)
<*> binaryDigits
)
)
[5, 50, 9000]
- Output:
5 -> 101 50 -> 110010 9000 -> 10001100101000
Icon and 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.
- Output:
5 = 101 50 = 110010 255 = 11111111 1285 = 10100000101 9000 = 10001100101000
Idris
module Main
binaryDigit : Integer -> Char
binaryDigit n = if (mod n 2) == 1 then '1' else '0'
binaryString : Integer -> String
binaryString 0 = "0"
binaryString n = pack (loop n [])
where loop : Integer -> List Char -> List Char
loop 0 acc = acc
loop n acc = loop (div n 2) (binaryDigit n :: acc)
main : IO ()
main = do
putStrLn (binaryString 0)
putStrLn (binaryString 5)
putStrLn (binaryString 50)
putStrLn (binaryString 9000)
- Output:
0 101 110010 10001100101000
J
Generate a list of binary digits and use it to select characters from string '01'.
tobin=: '01'{~#:
tobin 5
101
tobin 50
110010
tobin 9000
10001100101000
Uses implicit output.
Java
The Integer
class offers the toBinaryString
method.
Integer.toBinaryString(5);
Integer.toBinaryString(50);
Integer.toBinaryString(9000);
If you printed these values you would get the following.
101 110010 10001100101000
JavaScript
ES5
function toBinary(number) {
return new Number(number)
.toString(2);
}
var demoValues = [5, 50, 9000];
for (var i = 0; i < demoValues.length; ++i) {
// 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";
// ------------------ BINARY DIGITS ------------------
// showBinary :: Int -> String
const showBinary = n =>
showIntAtBase_(2)(n);
// showIntAtBase_ :: // Int -> Int -> String
const showIntAtBase_ = base =>
n => n.toString(base);
// ---------------------- TEST -----------------------
const main = () => [5, 50, 9000]
.map(n => `${n} -> ${showBinary(n)}`)
.join("\n");
// MAIN ---
return main();
})();
- Output:
5 -> 101 50 -> 110010 9000 -> 10001100101000
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";
// -------------- DIGITS FOR GIVEN BASE --------------
// showIntAtBase :: Int -> (Int -> Char) ->
// Int -> String -> String
const showIntAtBase = base =>
// A string representation of n, in the given base,
// using a supplied (Int -> Char) function for digits,
// and a supplied suffix string.
toChr => n => rs => {
const go = ([x, d], r) => {
const r_ = toChr(d) + r;
return 0 !== x ? (
go(quotRem(x)(base), r_)
) : r_;
};
const e = "error: showIntAtBase applied to";
return 1 >= base ? (
`${e} unsupported base`
) : 0 > n ? (
`${e} negative number`
) : go(quotRem(n)(base), rs);
};
// ---------------------- TEST -----------------------
const main = () => {
// showHanBinary :: Int -> String
const showHanBinary = n =>
showIntAtBase(2)(
x => "〇一" [x]
)(n)("");
return [5, 50, 9000]
.map(
n => `${n} -> ${showHanBinary(n)}`
)
.join("\n");
};
// --------------------- GENERIC ---------------------
// quotRem :: Integral a => a -> a -> (a, a)
const quotRem = m =>
// The quotient, tupled with the remainder.
n => [Math.trunc(m / n), m % n];
// MAIN ---
return main();
})();
- Output:
5 -> 一〇一 50 -> 一一〇〇一〇 9000 -> 一〇〇〇一一〇〇一〇一〇〇〇
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.
- Output:
["0" "1" "10" "101" "110010" "10001100101000"]
jq
def binary_digits:
[ recurse( ./2 | floor; . > 0) % 2 ] | reverse | join("") ;
# The task:
(5, 50, 9000) | binary_digits
- Output:
$ jq -n -r -f Binary_digits.jq 101 110010 10001100101000
Julia
using Printf
for n in (0, 5, 50, 9000)
@printf("%6i → %s\n", n, string(n, base=2))
end
# with pad
println("\nwith pad")
for n in (0, 5, 50, 9000)
@printf("%6i → %s\n", n, string(n, base=2, pad=20))
end
- Output:
0 → 0 5 → 101 50 → 110010 9000 → 10001100101000 with pad 0 → 00000000000000000000 5 → 00000000000000000101 50 → 00000000000000110010 9000 → 00000010001100101000
K
tobin: ,/$2_vs
tobin' 5 50 9000
("101"
"110010"
"10001100101000")
Kotlin
fun main() {
val numbers = intArrayOf(5, 50, 9000)
numbers.forEach { println("$it -> ${it.toString(2)}") }
}
- Output:
5 -> 101 50 -> 110010 9000 -> 10001100101000
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)
- Output:
0 1 10 101 110010 10001100101000
Lambdatalk
{def dec2bin
{lambda {:dec}
{if {= :dec 0}
then 0
else {if {< :dec 2}
then 1
else {dec2bin {floor {/ :dec 2}}}{% :dec 2} }}}}
-> dec2bin
{dec2bin 5} -> 101
{dec2bin 5} -> 110010
{dec2bin 9000} -> 10001100101000
{S.map dec2bin 5 50 9000}
-> 101 110010 10001100101000
{S.map {lambda {:i} {br}:i -> {dec2bin :i}} 5 50 9000}
->
5 -> 101
50 -> 110010
9000 -> 10001100101000
As a (faster) alternative we can ask some help from Javascript who knows how to do:
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
}
Lang
fn.println(fn.toTextBase(5, 2))
fn.println(fn.toTextBase(50, 2))
fn.println(fn.toTextBase(9000, 2))
Lang5
'%b '__number_format set
[5 50 9000] [3 1] reshape .
- Output:
[ [ 101 ] [ 110010 ] [ 10001100101000 ] ]
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))
If, however, you do need to get the results from a function, you can use (: erlang integer_to_list ... )
. Here's a simple example that does the same thing as the previous code:
(: lists foreach
(lambda (x)
(: io format
'"~s~n"
(list (: erlang integer_to_list x 2))))
(list 5 50 9000))
- Output (for both examples):
101 110010 10001100101000
Liberty BASIC
for a = 0 to 16
print a;"=";dec2bin$(a)
next
a=50:print a;"=";dec2bin$(a)
a=254:print a;"=";dec2bin$(a)
a=9000:print a;"=";dec2bin$(a)
wait
function dec2bin$(num)
if num=0 then dec2bin$="0":exit function
while num>0
dec2bin$=str$(num mod 2)+dec2bin$
num=int(num/2)
wend
end function
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.
// Little Man Computer, for Rosetta Code.
// Read numbers from user and display them in binary.
// Exit when input = 0.
input INP
BRZ zero
STA N
// Write number followed by '->'
OUT
LDA asc_hy
OTC
LDA asc_gt
OTC
// Find greatest power of 2 not exceeding N,
// and count how many digits will be output
LDA c1
STA pwr2
loop STA nrDigits
LDA N
SUB pwr2
SUB pwr2
BRP double
BRA part2 // jump out if next power of 2 would exceed N
double LDA pwr2
ADD pwr2
STA pwr2
LDA nrDigits
ADD c1
BRA loop
// Write the binary digits
part2 LDA N
SUB pwr2
set_diff STA diff
LDA asc_1 // first digit is always 1
wr_digit OTC // write digit
LDA nrDigits // count down the number of digits
SUB c1
BRZ input // if all digits done, loop for next number
STA nrDigits
// We now want to compare diff with pwr2/2.
// Since division is awkward in LMC, we compare 2*diff with pwr2.
LDA diff // diff := diff * 2
ADD diff
STA diff
SUB pwr2 // is diff >= pwr2 ?
BRP set_diff // yes, update diff and write '1'
LDA asc_0 // no, write '0'
BRA wr_digit
zero HLT // stop if input = 0
// Constants
c1 DAT 1
asc_hy DAT 45
asc_gt DAT 62
asc_0 DAT 48
asc_1 DAT 49
// Variables
N DAT
pwr2 DAT
nrDigits DAT
diff DAT
- Output:
5->101 50->110010 900->1110000100
LLVM
; ModuleID = 'binary.c'
; source_filename = "binary.c"
; target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
; target triple = "x86_64-pc-windows-msvc19.21.27702"
; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps
$"\01??_C@_03OFAPEBGM@?$CFs?6?$AA@" = comdat any
;--- String constant defintions
@"\01??_C@_03OFAPEBGM@?$CFs?6?$AA@" = linkonce_odr unnamed_addr constant [4 x i8] c"%s\0A\00", comdat, align 1
;--- The declaration for the external C printf function.
declare i32 @printf(i8*, ...)
;--- The declaration for the external C log10 function.
declare double @log10(double) #1
;--- The declaration for the external C malloc function.
declare noalias i8* @malloc(i64) #2
;--- The declaration for the external C free function.
declare void @free(i8*) #2
;----------------------------------------------------------
;-- Function that allocates a string with a binary representation of a number
define i8* @bin(i32) #0 {
;-- uint32_t x (local copy)
%2 = alloca i32, align 4
;-- size_t bits
%3 = alloca i64, align 8
;-- intermediate value
%4 = alloca i8*, align 8
;-- size_t i
%5 = alloca i64, align 8
store i32 %0, i32* %2, align 4
;-- x == 0, start determinig what value to initially store in bits
%6 = load i32, i32* %2, align 4
%7 = icmp eq i32 %6, 0
br i1 %7, label %just_one, label %calculate_logs
just_one:
br label %assign_bits
calculate_logs:
;-- log10((double) x)/log10(2) + 1
%8 = load i32, i32* %2, align 4
%9 = uitofp i32 %8 to double
;-- log10((double) x)
%10 = call double @log10(double %9) #3
;-- log10(2)
%11 = call double @log10(double 2.000000e+00) #3
;-- remainder of calculation
%12 = fdiv double %10, %11
%13 = fadd double %12, 1.000000e+00
br label %assign_bits
assign_bits:
;-- bits = (x == 0) ? 1 : log10((double) x)/log10(2) + 1;
;-- phi basically selects what the value to assign should be based on which basic block came before
%14 = phi double [ 1.000000e+00, %just_one ], [ %13, %calculate_logs ]
%15 = fptoui double %14 to i64
store i64 %15, i64* %3, align 8
;-- char *ret = malloc((bits + 1) * sizeof (char));
%16 = load i64, i64* %3, align 8
%17 = add i64 %16, 1
%18 = mul i64 %17, 1
%19 = call noalias i8* @malloc(i64 %18)
store i8* %19, i8** %4, align 8
store i64 0, i64* %5, align 8
br label %loop
loop:
;-- i < bits;
%20 = load i64, i64* %5, align 8
%21 = load i64, i64* %3, align 8
%22 = icmp ult i64 %20, %21
br i1 %22, label %loop_body, label %exit
loop_body:
;-- ret[bits - i - 1] = (x & 1) ? '1' : '0';
%23 = load i32, i32* %2, align 4
%24 = and i32 %23, 1
%25 = icmp ne i32 %24, 0
%26 = zext i1 %25 to i64
%27 = select i1 %25, i32 49, i32 48
%28 = trunc i32 %27 to i8
%29 = load i8*, i8** %4, align 8
%30 = load i64, i64* %3, align 8
%31 = load i64, i64* %5, align 8
%32 = sub i64 %30, %31
%33 = sub i64 %32, 1
%34 = getelementptr inbounds i8, i8* %29, i64 %33
store i8 %28, i8* %34, align 1
;-- x >>= 1;
%35 = load i32, i32* %2, align 4
%36 = lshr i32 %35, 1
store i32 %36, i32* %2, align 4
br label %loop_increment
loop_increment:
;-- i++;
%37 = load i64, i64* %5, align 8
%38 = add i64 %37, 1
store i64 %38, i64* %5, align 8
br label %loop
exit:
;-- ret[bits] = '\0';
%39 = load i8*, i8** %4, align 8
%40 = load i64, i64* %3, align 8
%41 = getelementptr inbounds i8, i8* %39, i64 %40
store i8 0, i8* %41, align 1
;-- return ret;
%42 = load i8*, i8** %4, align 8
ret i8* %42
}
;----------------------------------------------------------
;-- Entry point into the program
define i32 @main() #0 {
;-- 32-bit zero for the return
%1 = alloca i32, align 4
;-- size_t i, for tracking the loop index
%2 = alloca i64, align 8
;-- char* for the result of the bin call
%3 = alloca i8*, align 8
;-- initialize
store i32 0, i32* %1, align 4
store i64 0, i64* %2, align 8
br label %loop
loop:
;-- while (i < 20)
%4 = load i64, i64* %2, align 8
%5 = icmp ult i64 %4, 20
br i1 %5, label %loop_body, label %exit
loop_body:
;-- char *binstr = bin(i);
%6 = load i64, i64* %2, align 8
%7 = trunc i64 %6 to i32
%8 = call i8* @bin(i32 %7)
store i8* %8, i8** %3, align 8
;-- printf("%s\n", binstr);
%9 = load i8*, i8** %3, align 8
%10 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01??_C@_03OFAPEBGM@?$CFs?6?$AA@", i32 0, i32 0), i8* %9)
;-- free(binstr);
%11 = load i8*, i8** %3, align 8
call void @free(i8* %11)
br label %loop_increment
loop_increment:
;-- i++
%12 = load i64, i64* %2, align 8
%13 = add i64 %12, 1
store i64 %13, i64* %2, align 8
br label %loop
exit:
;-- return 0 (implicit)
%14 = load i32, i32* %1, align 4
ret i32 %14
}
attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { nounwind "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #2 = { "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #3 = { nounwind }
!llvm.module.flags = !{!0, !1}
!llvm.ident = !{!2}
!0 = !{i32 1, !"wchar_size", i32 2}
!1 = !{i32 7, !"PIC Level", i32 2}
!2 = !{!"clang version 6.0.1 (tags/RELEASE_601/final)"}
- Output:
0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 10000 10001 10010 10011
Locomotive Basic
10 PRINT BIN$(5)
20 PRINT BIN$(50)
30 PRINT BIN$(9000)
- Output:
101 110010 10001100101000
LOLCODE
HAI 1.3
HOW IZ I DECIMULBINUR YR DECIMUL
I HAS A BINUR ITZ ""
IM IN YR DUUH
BOTH SAEM DECIMUL AN SMALLR OF DECIMUL AN 0, O RLY?
YA RLY, GTFO
OIC
BINUR R SMOOSH MOD OF DECIMUL AN 2 BINUR MKAY
DECIMUL R MAEK QUOSHUNT OF DECIMUL AN 2 A NUMBR
IM OUTTA YR DUUH
FOUND YR BINUR
IF U SAY SO
VISIBLE I IZ DECIMULBINUR YR 5 MKAY
VISIBLE I IZ DECIMULBINUR YR 50 MKAY
VISIBLE I IZ DECIMULBINUR YR 9000 MKAY
KTHXBYE
- Output:
101 110010 10001100101000
LSL
/* This script could convert base10 to any base number system, & in any symbol-set
charset can be anything, any symbols, but the frist one should be the zero symbol */
string charset = "01";
string int2chr(integer int) {
// convert integer to unsigned charset
integer base = llStringLength(charset);
string out;
integer j;
if(int < 0) {
j = ((0x7FFFFFFF & int) % base) - (0x80000000 % base);
integer k = j % base;
int = (j / base) + ((0x7FFFFFFF & int) / base) - (0x80000000 / base);
out = llGetSubString(charset, k, k);
}
do
out = llGetSubString(charset, j = int % base, j) + out;
while(int /= base);
return out;
}
integer chr2int(string chr) {
// convert unsigned charset to integer
integer base = llStringLength(charset);
integer i = -llStringLength(chr);
integer j = 0;
while(i)
j = (j * base) + llSubStringIndex(charset, llGetSubString(chr, i, i++));
return j;
}
string pad (string input, integer width)
{
integer i=llStringLength(input);
string zero=llGetSubString(charset,0,0);
//first symbol of charset should be for zero
// add padding if necessary
while(width>i)
{
i=i+1;
input=zero+input; // prepend string and loop
}
// take away padding if necessary
while(width<i)
// do this if padding length is less than input
{ i=i-1;
if((llGetSubString(input, 0, 0))==zero)
{
// eat first leading bit if it's a zero symbol
input=llDeleteSubString(input,0,0);
//equivalent to input=llGetSubString(input,1,-1);
}
else{width=i;}
// to break loop stop if not a leading zero
}
return input;
}
default
{ // Default state is where script starts
state_entry()
{
integer a = 42;
llOwnerSay((string)a);
string output = int2chr(a); // dec to bin
llOwnerSay(output);
output=pad(output,10); // add padding
llOwnerSay(output);
output=pad(output,0); // take away padding
llOwnerSay(output);
llOwnerSay( (string)chr2int(output) ); // bin to dec
}
}
- Output:
Object: 42 Object: 101010 Object: 0000101010 Object: 101010 Object: 42
Lua
Lua - Iterative
function dec2bin(n)
local bin = ""
while n > 1 do
bin = n % 2 .. bin
n = math.floor(n / 2)
end
return n .. bin
end
print(dec2bin(5))
print(dec2bin(50))
print(dec2bin(9000))
- Output:
101 110010 10001100101000
Lua - Recursive
-- 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))
- Output:
101 110010 10001100101000
M2000 Interpreter
Module Checkit {
Form 90, 40
Function BinFunc${
Dim Base 0, One$(16)
One$( 0 ) = "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
=lambda$ One$() (x, oct as long=4, bypass as boolean=True) ->{
if oct>0 and oct<5 then {
oct=2*(int(4-oct) mod 4+1)-1
} Else oct=1
hx$ = Hex$(x, 4 )
Def Ret$
If Bypass then {
For i= oct to len(hx$)
if bypass Then if Mid$(hx$, i, 1 )="0" Else bypass=false
If bypass and i<>Len(hx$) Then Continue
Ret$ += One$( EVal( "0x" + Mid$(hx$, i, 1 ) ) )
Next i
oct=instr(Ret$, "1")
if oct=0 then {
Ret$="0"
} Else Ret$=mid$(Ret$, oct)
} Else {
For i= oct to len(hx$)
Ret$ += One$( EVal( "0x" + Mid$(hx$, i, 1 ) ) )
Next i
}
=Ret$
}
}
Bin$=BinFunc$()
Stack New {
Data 9, 50, 9000
While not empty {
Read x
Print Format$("The decimal value {0::-10} should produce an output of {1:-32}",x, Bin$(x) )
}
}
Stack New {
Data 9, 50, 9000
While not empty {
Read x
Print Format$("The decimal value {0::-10} should produce an output of {1:-32}",x, Bin$(x,,false) )
}
}
Stack New {
Data 9, 50, 9000
While not empty {
Read x
Print Bin$(x)
}
}
}
Checkit
- Output:
The decimal value 9 should produce an output of 1001 The decimal value 50 should produce an output of 110010 The decimal value 9000 should produce an output of 10001100101000 The decimal value 9 should produce an output of 00000000000000000000000000001001 The decimal value 50 should produce an output of 00000000000000000000000000110010 The decimal value 9000 should produce an output of 00000000000000000010001100101000 1001 110010 10001100101000
MACRO-11
.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
- Output:
101 110010 10001100101000
MAD
MAD has basically no support for runtime generation of strings.
Therefore, this program works by calculating an integer whose decimal representation
matches the binary representation of the input, e.g. BINARY.(5)
is 101
.
NORMAL MODE IS INTEGER
INTERNAL FUNCTION(NUM)
ENTRY TO BINARY.
BTEMP = NUM
BRSLT = 0
BDIGIT = 1
BIT WHENEVER BTEMP.NE.0
BRSLT = BRSLT + BDIGIT * (BTEMP-BTEMP/2*2)
BTEMP = BTEMP/2
BDIGIT = BDIGIT * 10
TRANSFER TO BIT
END OF CONDITIONAL
FUNCTION RETURN BRSLT
END OF FUNCTION
THROUGH SHOW, FOR VALUES OF N = 5, 50, 9000
SHOW PRINT FORMAT FMT, N, BINARY.(N)
VECTOR VALUES FMT = $I4,2H: ,I16*$
END OF PROGRAM
- Output:
5: 101 50: 110010 9000: 10001100101000
Maple
> convert( 50, 'binary' );
110010
> convert( 9000, 'binary' );
10001100101000
Mathematica / Wolfram Language
StringJoin @@ ToString /@ IntegerDigits[50, 2]
MATLAB / Octave
dec2bin(5)
dec2bin(50)
dec2bin(9000)
The output is a string containing ascii(48) (i.e. '0') and ascii(49) (i.e. '1').
Maxima
digits([arg]) := block(
[n: first(arg), b: if length(arg) > 1 then second(arg) else 10, v: [ ], q],
do (
[n, q]: divide(n, b),
v: cons(q, v),
if n=0 then return(v)))$
binary(n) := simplode(digits(n, 2))$
binary(9000);
/*
10001100101000
*/
MAXScript
-- MAXScript: Output decimal numbers from 0 to 16 as Binary : N.H. 2019
for k = 0 to 16 do
(
temp = ""
binString = ""
b = k
-- While loop wont execute for zero so force string to zero
if b == 0 then temp = "0"
while b > 0 do
(
rem = b
b = b / 2
If ((mod rem 2) as Integer) == 0 then temp = temp + "0"
else temp = temp + "1"
)
-- Reverse the binary string
for r = temp.count to 1 by -1 do
(
binString = binString + temp[r]
)
print binString
)
- Output:
Output to MAXScript Listener:
"0" "1" "10" "11" "100" "101" "110" "111" "1000" "1001" "1010" "1011" "1100" "1101" "1110" "1111" "10000"
Mercury
:- module binary_digits.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module int, list, string.
main(!IO) :-
list.foldl(print_binary_digits, [5, 50, 9000], !IO).
:- pred print_binary_digits(int::in, io::di, io::uo) is det.
print_binary_digits(N, !IO) :-
io.write_string(int_to_base_string(N, 2), !IO),
io.nl(!IO).
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!
- Output:
0, 1, 10, 101, 110010, 10001100101000
MiniScript
Iterative
binary = function(n)
result = ""
while n
result = str(n%2) + result
n = floor(n/2)
end while
if not result then return "0"
return result
end function
print binary(5)
print binary(50)
print binary(9000)
print binary(0)
Recursive
binary = function(n,result="")
if n == 0 then
if result == "" then return "0" else return result
end if
result = str(n%2) + result
return binary(floor(n/2),result)
end function
print binary(5)
print binary(50)
print binary(9000)
print binary(0)
- Output:
101 110010 10001100101000 0
mLite
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, [])
;
from the REPL
mLite > binary 5; "101" > binary 50; "110010" > binary 9000; "10001100101000"
Modula-2
MODULE Binary;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT Write,WriteLn,ReadChar;
PROCEDURE PrintByte(b : INTEGER);
VAR v : INTEGER;
BEGIN
v := 080H;
WHILE v#0 DO
IF (b BAND v) # 0 THEN
Write('1')
ELSE
Write('0')
END;
v := v SHR 1
END
END PrintByte;
VAR
buf : ARRAY[0..15] OF CHAR;
i : INTEGER;
BEGIN
FOR i:=0 TO 15 DO
PrintByte(i);
WriteLn
END;
ReadChar
END Binary.
Modula-3
MODULE Binary EXPORTS Main;
IMPORT IO, Fmt;
VAR num := 10;
BEGIN
IO.Put(Fmt.Int(num, 2) & "\n");
num := 150;
IO.Put(Fmt.Int(num, 2) & "\n");
END Binary.
- Output:
1010 10010110
NetRexx
/* NetRexx */
options replace format comments java crossref symbols nobinary
runSample(arg)
return
method getBinaryDigits(nr) public static
bd = nr.d2x.x2b.strip('L', 0)
if bd.length = 0 then bd = 0
return bd
method runSample(arg) public static
parse arg list
if list = '' then list = '0 5 50 9000'
loop n_ = 1 to list.words
w_ = list.word(n_)
say w_.right(20)':' getBinaryDigits(w_)
end n_
- Output:
0: 0 5: 101 50: 110010 9000: 10001100101000
NewLisp
;;; Using the built-in "bits" function
;;; For integers up to 9,223,372,036,854,775,807
(map println (map bits '(0 5 50 9000)))
;;; n > 0, "unlimited" size
(define (big-bits n)
(let (res "")
(while (> n 0)
(push (if (even? n) "0" "1") res)
(setq n (/ n 2)))
res))
;;; Example
(println (big-bits 1234567890123456789012345678901234567890L))
Output: 0 101 110010 10001100101000 1110100000110010010010000001110101110000001101101111110011101110001010110010111100010111111001011011001110001111110000101011010010
Nickle
Using the Nickle output radix operator:
prompt$ nickle > 0 # 2 0 > 5 # 2 101 > 50 # 2 110010 > 9000 # 2 10001100101000
Nim
proc binDigits(x: BiggestInt, r: int): int =
## Calculates how many digits `x` has when each digit covers `r` bits.
result = 1
var y = x shr r
while y > 0:
y = y shr r
inc(result)
proc toBin*(x: BiggestInt, len: Natural = 0): string =
## converts `x` into its binary representation. The resulting string is
## always `len` characters long. By default the length is determined
## automatically. No leading ``0b`` prefix is generated.
var
mask: BiggestInt = 1
shift: BiggestInt = 0
len = if len == 0: binDigits(x, 1) else: len
result = newString(len)
for j in countdown(len-1, 0):
result[j] = chr(int((x and mask) shr shift) + ord('0'))
shift = shift + 1
mask = mask shl 1
for i in 0..15:
echo toBin(i)
- Output:
0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111
Version using strformat
import strformat
for n in 0..15:
echo fmt"{n:b}"
- Output:
0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111
Nu
def bin [x] { $x | (fmt).binary | str substring 2.. }
[0 1 2 5 50 9000] | each { {dec: $in bin: (bin $in)} }
- Output:
╭───┬──────┬────────────────╮ │ # │ dec │ bin │ ├───┼──────┼────────────────┤ │ 0 │ 0 │ 0 │ │ 1 │ 1 │ 1 │ │ 2 │ 2 │ 10 │ │ 3 │ 5 │ 101 │ │ 4 │ 50 │ 110010 │ │ 5 │ 9000 │ 10001100101000 │ ╰───┴──────┴────────────────╯
Oberon-2
MODULE BinaryDigits;
IMPORT Out;
PROCEDURE OutBin(x: INTEGER);
BEGIN
IF x > 1 THEN OutBin(x DIV 2) END;
Out.Int(x MOD 2, 1);
END OutBin;
BEGIN
OutBin(0); Out.Ln;
OutBin(1); Out.Ln;
OutBin(2); Out.Ln;
OutBin(3); Out.Ln;
OutBin(42); Out.Ln;
END BinaryDigits.
- Output:
0 1 10 11 101010
Objeck
class Binary {
function : Main(args : String[]) ~ Nil {
5->ToBinaryString()->PrintLine();
50->ToBinaryString()->PrintLine();
9000->ToBinaryString()->PrintLine();
}
}
- Output:
101 110010 10001100101000
OCaml
let bin_of_int d =
let last_digit n = [|"0"; "1"|].(n land 1) in
let rec aux lst = function
| 0 -> lst
| n -> aux (last_digit n :: lst) (n lsr 1)
in
String.concat "" (aux [last_digit d] (d lsr 1))
(* test *)
let () = [0; 1; 2; 5; 50; 9000; -5]
|> List.map bin_of_int |> String.concat ", " |> print_endline
The output of negative integers is interesting, as it shows the two's complement representation and the width of Int on the system.
- Output:
0, 1, 10, 101, 110010, 10001100101000, 1111111111111111111111111111011
Oforth
- Output:
>5 asStringOfBase(2) println 101 ok >50 asStringOfBase(2) println 110010 ok >9000 asStringOfBase(2) println 10001100101000 ok >423785674235000123456789 asStringOfBase(2) println 1011001101111010111011110101001101111000000000000110001100000100111110100010101 ok
Ol
(print (number->string 5 2))
(print (number->string 50 2))
(print (number->string 9000 2))
- Output:
101 110010 10001100101000
OxygenBasic
The Assembly code uses block structures to minimise the use of labels.
function BinaryBits(sys n) as string
string buf=nuls 32
sys p=strptr buf
sys le
mov eax,n
mov edi,p
mov ecx,32
'
'STRIP LEADING ZEROS
(
dec ecx
jl fwd done
shl eax,1
jnc repeat
)
'PLACE DIGITS
'
mov byte [edi],49 '1'
inc edi
(
cmp ecx,0
jle exit
mov dl,48 '0'
shl eax,1
(
jnc exit
mov dl,49 '1'
)
mov [edi],dl
inc edi
dec ecx
repeat
)
done:
'
sub edi,p
mov le,edi
if le then return left buf,le
return "0"
end function
print BinaryBits 0xaa 'result 10101010
Panda
0..15.radix:2 nl
- Output:
0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111
PARI/GP
bin(n:int)=concat(apply(s->Str(s),binary(n)))
Pascal
FPC compiler Version 2.6 upwards.The obvious version.
program IntToBinTest;
{$MODE objFPC}
uses
strutils;//IntToBin
function WholeIntToBin(n: NativeUInt):string;
var
digits: NativeInt;
begin
// BSR?Word -> index of highest set bit but 0 -> 255 ==-1 )
IF n <> 0 then
Begin
{$ifdef CPU64}
digits:= BSRQWord(NativeInt(n))+1;
{$ELSE}
digits:= BSRDWord(NativeInt(n))+1;
{$ENDIF}
WholeIntToBin := IntToBin(NativeInt(n),digits);
end
else
WholeIntToBin:='0';
end;
procedure IntBinTest(n: NativeUint);
Begin
writeln(n:12,' ',WholeIntToBin(n));
end;
BEGIN
IntBinTest(5);IntBinTest(50);IntBinTest(5000);
IntBinTest(0);IntBinTest(NativeUint(-1));
end.
- Output:
5 101 50 110010 5000 1001110001000 0 0 18446744073709551615 1111111111111111111111111111111111111111111111111111111111111111
alternative 4 chars at a time
using pchar like C insert one nibble at a time. Beware of the endianess of the constant. I check performance with random Data.
program IntToPcharTest;
uses
sysutils;//for timing
const
{$ifdef CPU64}
cBitcnt = 64;
{$ELSE}
cBitcnt = 32;
{$ENDIF}
procedure IntToBinPchar(AInt : NativeUInt;s:pChar);
//create the Bin-String
//!Beware of endianess ! this is for little endian
const
IO : array[0..1] of char = ('0','1');//('_','X'); as you like
IO4 : array[0..15] of LongWord = // '0000','1000' as LongWord
($30303030,$31303030,$30313030,$31313030,
$30303130,$31303130,$30313130,$31313130,
$30303031,$31303031,$30313031,$31313031,
$30303131,$31303131,$30313131,$31313131);
var
i : NativeInt;
begin
IF AInt > 0 then
Begin
// Get the index of highest set bit
{$ifdef CPU64}
i := BSRQWord(NativeInt(Aint))+1;
{$ELSE}
i := BSRDWord(NativeInt(Aint))+1;
{$ENDIF}
s[i] := #0;
//get 4 characters at once
dec(i);
while i >= 3 do
Begin
pLongInt(@s[i-3])^ := IO4[Aint AND 15];
Aint := Aint SHR 4;
dec(i,4)
end;
//the rest one by one
while i >= 0 do
Begin
s[i] := IO[Aint AND 1];
AInt := Aint shr 1;
dec(i);
end;
end
else
Begin
s[0] := IO[0];
s[1] := #0;
end;
end;
procedure Binary_Digits;
var
s: pCHar;
begin
GetMem(s,cBitcnt+4);
fillchar(s[0],cBitcnt+4,#0);
IntToBinPchar( 5,s);writeln(' 5: ',s);
IntToBinPchar( 50,s);writeln(' 50: ',s);
IntToBinPchar(9000,s);writeln('9000: ',s);
IntToBinPchar(NativeUInt(-1),s);writeln(' -1: ',s);
FreeMem(s);
end;
const
rounds = 10*1000*1000;
var
s: pChar;
t :TDateTime;
i,l,cnt: NativeInt;
Testfield : array[0..rounds-1] of NativeUint;
Begin
randomize;
cnt := 0;
For i := rounds downto 1 do
Begin
l := random(High(NativeInt));
Testfield[i] := l;
{$ifdef CPU64}
inc(cnt,BSRQWord(l));
{$ELSE}
inc(cnt,BSRQWord(l));
{$ENDIF}
end;
Binary_Digits;
GetMem(s,cBitcnt+4);
fillchar(s[0],cBitcnt+4,#0);
//warm up
For i := 0 to rounds-1 do
IntToBinPchar(Testfield[i],s);
//speed test
t := time;
For i := 1 to rounds do
IntToBinPchar(Testfield[i],s);
t := time-t;
Write(' Time ',t*86400.0:6:3,' secs, average stringlength ');
Writeln(cnt/rounds+1:6:3);
FreeMem(s);
end.
- Output:
//32-Bit fpc 3.1.1 -O3 -XX -Xs Cpu i4330 @3.5 Ghz 5: 101 50: 110010 9000: 10001100101000 -1: 11111111111111111111111111111111 Time 0.133 secs, average stringlength 30.000 //64-Bit fpc 3.1.1 -O3 -XX -Xs ... -1: 1111111111111111111111111111111111111111111111111111111111111111 Time 0.175 secs, average stringlength 62.000 ..the obvious version takes about 1.1 secs generating the string takes most of the time..
PascalABC.NET
begin
foreach var number in |5, 50, 9000| do
Writeln($'{number,4} - {Convert.ToString(number,2)}');
end.
- Output:
5 - 101 50 - 110010 9000 - 10001100101000
Peloton
<@ defbaslit>2</@>
<@ saybaslit>0</@>
<@ saybaslit>5</@>
<@ saybaslit>50</@>
<@ saybaslit>9000</@>
Perl
for (5, 50, 9000) {
printf "%b\n", $_;
}
101 110010 10001100101000
Phix
printf(1,"%b\n",5) printf(1,"%b\n",50) printf(1,"%b\n",9000)
- Output:
101 110010 10001100101000
Phixmonti
def printBinary
"The decimal value " print dup print " should produce an output of " print
20 int>bit
len 1 -1 3 tolist
for
get not
if
-1 del
else
exitfor
endif
endfor
len 1 -1 3 tolist
for
get print
endfor
nl
enddef
5 printBinary
50 printBinary
9000 printBinary
Other solution
/# Rosetta Code problem: http://rosettacode.org/wiki/Binary_digits
by Galileo, 05/2022 #/
include ..\Utilitys.pmt
def printBinary
0 >ps >ps
( "The decimal value " tps " should produce an output of " ) lprint
ps> 20 int>bit
( len 1 -1 ) for
get dup ps> or if print 1 >ps else drop 0 >ps endif
endfor
nl
enddef
5 printBinary
50 printBinary
9000 printBinary
- Output:
The decimal value 5 should produce an output of 101 The decimal value 50 should produce an output of 110010 The decimal value 9000 should produce an output of 10001100101000 === Press any key to exit ===
PHP
<?php
echo decbin(5);
echo decbin(50);
echo decbin(9000);
- Output:
101 110010 10001100101000
Picat
foreach(I in [5,50,900])
println(to_binary_string(I))
end.
- Output:
101 110010 1110000100
PicoLisp
: (bin 5)
-> "101"
: (bin 50)
-> "110010"
: (bin 9000)
-> "10001100101000"
Piet
Rendered as wikitable, because image upload is not possible:
ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww |
ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww |
ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww |
ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww |
ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww |
ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww |
ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww | ww |
Examples:
? 5 101 ? 50 110010 ? 9000 10001100101000
Explanation of program flow and image download link on my user page: [1]
PL/I
Displays binary output trivially, but with leading zeros:
put edit (25) (B);
- Output:
Output: 0011001
With leading zero suppression:
declare text character (50) initial (' ');
put string(text) edit (25) (b);
put skip list (trim(text, '0'));
put string(text) edit (2147483647) (b);
put skip list (trim(text, '0'));
- Output:
11001 1111111111111111111111111111111
PL/M
100H:
/* CP/M BDOS CALL */
BDOS: PROCEDURE (FN, ARG);
DECLARE FN BYTE, ARG ADDRESS;
GO TO 5;
END BDOS;
/* PRINT STRING */
PRINT: PROCEDURE (STRING);
DECLARE STRING ADDRESS;
CALL BDOS(9, STRING);
END PRINT;
/* PRINT BINARY NUMBER */
PRINT$BINARY: PROCEDURE (N);
DECLARE S (19) BYTE INITIAL ('................',13,10,'$');
DECLARE (N, P) ADDRESS, C BASED P BYTE;
P = .S(16);
BIT:
P = P - 1;
C = (N AND 1) + '0';
IF (N := SHR(N,1)) <> 0 THEN GO TO BIT;
CALL PRINT(P);
END PRINT$BINARY;
/* EXAMPLES FROM TASK */
DECLARE TEST (3) ADDRESS INITIAL (5, 50, 9000);
DECLARE I BYTE;
DO I = 0 TO LAST(TEST);
CALL PRINT$BINARY(TEST(I));
END;
CALL BDOS(0,0);
EOF
- Output:
101 110010 10001100101000
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
#COMPILER PBCC 6
FUNCTION PBMAIN () AS LONG
LOCAL i, d() AS DWORD
REDIM d(2)
ARRAY ASSIGN d() = 5, 50, 9000
FOR i = 0 TO 2
PRINT STR$(d(i)) & ": " & BIN$(d(i)) & " (" & BIN$(d(i), 32) & ")"
NEXT i
END FUNCTION
- Output:
5: 101 (00000000000000000000000000000101) 50: 110010 (00000000000000000000000000110010) 9000: 10001100101000 (00000000000000000010001100101000)
PowerShell
@(5,50,900) | foreach-object { [Convert]::ToString($_,2) }
- Output:
101 110010 1110000100
Processing
println(Integer.toBinaryString(5)); // 101
println(Integer.toBinaryString(50)); // 110010
println(Integer.toBinaryString(9000)); // 10001100101000
Processing also has a binary() function, but this returns zero-padded results
println(binary(5)); // 00000000000101
println(binary(50)); // 00000000110010
println(binary(9000)); // 10001100101000
Prolog
binary(X) :- format('~2r~n', [X]).
main :- maplist(binary, [5,50,9000]), halt.
- Output:
101 110010 10001100101000
PureBasic
If OpenConsole()
PrintN(Bin(5)) ;101
PrintN(Bin(50)) ;110010
PrintN(Bin(9000)) ;10001100101000
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf
- Output:
101 110010 10001100101000
Python
String.format() method
>>> for i in range(16): print('{0:b}'.format(i))
0
1
10
11
100
101
110
111
1000
1001
1010
1011
1100
1101
1110
1111
Built-in bin() function
>>> for i in range(16): print(bin(i)[2:])
0
1
10
11
100
101
110
111
1000
1001
1010
1011
1100
1101
1110
1111
Pre-Python 2.6:
>>> 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))
0
1
10
11
100
101
110
111
1000
1001
1010
1011
1100
1101
1110
1111
Custom functions
Defined in terms of a more general showIntAtBase function:
'''Binary strings for integers'''
# showBinary :: Int -> String
def showBinary(n):
'''Binary string representation of an integer.'''
def binaryChar(n):
return '1' if n != 0 else '0'
return showIntAtBase(2)(binaryChar)(n)('')
# TEST ----------------------------------------------------
# main :: IO()
def main():
'''Test'''
print('Mapping showBinary over integer list:')
print(unlines(map(
showBinary,
[5, 50, 9000]
)))
print(tabulated(
'\nUsing showBinary as a display function:'
)(str)(showBinary)(
lambda x: x
)([5, 50, 9000]))
# GENERIC -------------------------------------------------
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
# showIntAtBase :: Int -> (Int -> String) -> Int -> String -> String
def showIntAtBase(base):
'''String representing a non-negative integer
using the base specified by the first argument,
and the character representation specified by the second.
The final argument is a (possibly empty) string to which
the numeric string will be prepended.'''
def wrap(toChr, n, rs):
def go(nd, r):
n, d = nd
r_ = toChr(d) + r
return go(divmod(n, base), r_) if 0 != n else r_
return 'unsupported base' if 1 >= base else (
'negative number' if 0 > n else (
go(divmod(n, base), rs))
)
return lambda toChr: lambda n: lambda rs: (
wrap(toChr, n, rs)
)
# tabulated :: String -> (a -> String) ->
# (b -> String) ->
# (a -> b) -> [a] -> String
def tabulated(s):
'''Heading -> x display function -> fx display function ->
f -> value list -> tabular string.'''
def go(xShow, fxShow, f, xs):
w = max(map(compose(len)(xShow), xs))
return s + '\n' + '\n'.join(
xShow(x).rjust(w, ' ') + ' -> ' + fxShow(f(x)) for x in xs
)
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
# unlines :: [String] -> String
def unlines(xs):
'''A single string derived by the intercalation
of a list of strings with the newline character.'''
return '\n'.join(xs)
if __name__ == '__main__':
main()
- Output:
Mapping showBinary over integer list: 101 110010 10001100101000 Using showBinary as a display function: 5 -> 101 50 -> 110010 9000 -> 10001100101000
Or, using a more specialised function to decompose an integer to a list of boolean values:
'''Decomposition of an integer to a string of booleans.'''
# boolsFromInt :: Int -> [Bool]
def boolsFromInt(n):
'''List of booleans derived by binary
decomposition of an integer.'''
def go(x):
(q, r) = divmod(x, 2)
return Just((q, bool(r))) if x else Nothing()
return unfoldl(go)(n)
# stringFromBools :: [Bool] -> String
def stringFromBools(xs):
'''Binary string representation of a
list of boolean values.'''
def oneOrZero(x):
return '1' if x else '0'
return ''.join(map(oneOrZero, xs))
# TEST ----------------------------------------------------
# main :: IO()
def main():
'''Test'''
binary = compose(stringFromBools)(boolsFromInt)
print('Mapping a composed function:')
print(unlines(map(
binary,
[5, 50, 9000]
)))
print(
tabulated(
'\n\nTabulating a string display from binary data:'
)(str)(stringFromBools)(
boolsFromInt
)([5, 50, 9000])
)
# GENERIC -------------------------------------------------
# Just :: a -> Maybe a
def Just(x):
'''Constructor for an inhabited Maybe (option type) value.'''
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
# Nothing :: Maybe a
def Nothing():
'''Constructor for an empty Maybe (option type) value.'''
return {'type': 'Maybe', 'Nothing': True}
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
# tabulated :: String -> (a -> String) ->
# (b -> String) ->
# (a -> b) -> [a] -> String
def tabulated(s):
'''Heading -> x display function -> fx display function ->
f -> value list -> tabular string.'''
def go(xShow, fxShow, f, xs):
w = max(map(compose(len)(xShow), xs))
return s + '\n' + '\n'.join(
xShow(x).rjust(w, ' ') + ' -> ' + fxShow(f(x)) for x in xs
)
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
# unfoldl(lambda x: Just(((x - 1), x)) if 0 != x else Nothing())(10)
# -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# unfoldl :: (b -> Maybe (b, a)) -> b -> [a]
def unfoldl(f):
'''Dual to reduce or foldl.
Where these reduce a list to a summary value, unfoldl
builds a list from a seed value.
Where f returns Just(a, b), a is appended to the list,
and the residual b is used as the argument for the next
application of f.
When f returns Nothing, the completed list is returned.'''
def go(v):
xr = v, v
xs = []
while True:
mb = f(xr[0])
if mb.get('Nothing'):
return xs
else:
xr = mb.get('Just')
xs.insert(0, xr[1])
return xs
return lambda x: go(x)
# unlines :: [String] -> String
def unlines(xs):
'''A single string derived by the intercalation
of a list of strings with the newline character.'''
return '\n'.join(xs)
# MAIN -------------------------------------------------
if __name__ == '__main__':
main()
- Output:
Mapping a composed function: 101 110010 10001100101000 Tabulating a string display from binary data: 5 -> 101 50 -> 110010 9000 -> 10001100101000
QB64
Print DecToBin$(5)
Print DecToBin$(50)
Print DecToBin$(9000)
Print BinToDec$(DecToBin$(5)) ' 101
Print BinToDec$(DecToBin$(50)) '110010
Print BinToDec$(DecToBin$(9000)) ' 10001100101000
End
Function DecToBin$ (digit As Integer)
DecToBin$ = "Error"
If digit < 1 Then
Print " Error number invalid for conversion to binary"
DecToBin$ = "error of input"
Exit Function
Else
Dim As Integer TempD
Dim binaryD As String
binaryD = ""
TempD = digit
Do
binaryD = Right$(Str$(TempD Mod 2), 1) + binaryD
TempD = TempD \ 2
Loop Until TempD = 0
DecToBin$ = binaryD
End If
End Function
Function BinToDec$ (digitB As String)
BinToDec$ = "Error"
If Len(digitB) < 1 Then
Print " Error number invalid for conversion to decimal"
BinToDec$ = "error of input"
Exit Function
Else
Dim As Integer TempD
Dim binaryD As String
binaryD = digitB
TempD = 0
Do
TempD = TempD + ((2 ^ (Len(binaryD) - 1)) * Val(Left$(binaryD, 1)))
binaryD = Right$(binaryD, Len(binaryD) - 1)
Loop Until Len(binaryD) = 0
BinToDec$ = LTrim$(Str$(TempD))
End If
End Function
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. )
5 echo cr
50 echo cr
9000 echo cr
base release ( It's best to clean up after ourselves. )
( Numbers will be output in base 10 now. )
A user-defined conversion might look something like this:
[ [] swap
[ 2 /mod digit
swap dip join
dup not until ]
drop reverse ] is bin ( n --> $ )
5 bin echo$ cr
50 bin echo$ cr
9000 bin echo$ cr
- Output:
101 110010 10001100101000
R
dec2bin <- function(num) {
ifelse(num == 0,
0,
sub("^0+","",paste(rev(as.integer(intToBits(num))), collapse = ""))
)
}
for (anumber in c(0, 5, 50, 9000)) {
cat(dec2bin(anumber),"\n")
}
output
0 101 110010 10001100101000
Racket
#lang racket
;; Option 1: binary formatter
(for ([i 16]) (printf "~b\n" i))
;; Option 2: explicit conversion
(for ([i 16]) (displayln (number->string i 2)))
Raku
(formerly Perl 6)
say .fmt("%b") for 5, 50, 9000;
101 110010 10001100101000
Alternatively:
say .base(2) for 5, 50, 9000;
101 110010 10001100101000
RapidQ
'Convert Integer to binary string
Print "bin 5 = ", bin$(5)
Print "bin 50 = ",bin$(50)
Print "bin 9000 = ",bin$(9000)
sleep 10
Red
Red []
foreach number [5 50 9000] [
;; any returns first not false value, used to cut leading zeroes
binstr: form any [find enbase/base to-binary number 2 "1" "0"]
print reduce [ pad/left number 5 binstr ]
]
output
5 101 50 110010 9000 10001100101000
Retro
9000 50 5 3 [ binary putn cr decimal ] times
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>;
};
{{out}
101 110010 10001100101000
REXX
This version handles the special case of zero simply.
simple version
Note: some REXX interpreters have a D2B [Decimal to Binary] BIF (built-in function).
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).
/*REXX program to convert several decimal numbers to binary (or base 2). */
numeric digits 1000 /*ensure we can handle larger numbers. */
@.=; @.1= 0
@.2= 5
@.3= 50
@.4= 9000
do j=1 while @.j\=='' /*compute until a NULL value is found.*/
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. */
- output:
0 decimal, and in binary: 0 5 decimal, and in binary: 101 50 decimal, and in binary: 110010 9000 decimal, and in binary: 10001100101000
elegant version
This version handles the case of zero as a special case more elegantly.
The following versions depend on the setting of numeric digits such that the number in decimal can be expressed as a whole number.
/*REXX program to convert several decimal numbers to binary (or base 2). */
@.=; @.1= 0
@.2= 5
@.3= 50
@.4= 9000
do j=1 while @.j\=='' /*compute until a NULL value is found.*/
y=strip( x2b( d2x( @.j )), 'L', 0) /*force removal of all leading zeroes.*/
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. */
- output is identical to the 1st REXX version.
concise version
This version handles the case of zero a bit more obtusely, but concisely.
/*REXX program to convert several decimal numbers to binary (or base 2). */
@.=; @.1= 0
@.2= 5
@.3= 50
@.4= 9000
do j=1 while @.j\=='' /*compute until a NULL value is found.*/
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. */
- output is identical to the 1st REXX version.
conforming version
This REXX version conforms to the strict output requirements of this task (just show the binary output without any blanks).
/*REXX program to convert several decimal numbers to binary (or base 2). */
numeric digits 200 /*ensure we can handle larger numbers. */
@.=; @.1= 0
@.2= 5
@.3= 50
@.4= 9000
@.5=423785674235000123456789
@.6= 1e138 /*one quinquaquadragintillion ugh.*/
do j=1 while @.j\=='' /*compute until a NULL value is found.*/
y=strip( x2b( d2x( @.j )), 'L', 0) /*force removal of all leading zeroes.*/
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. */
- output:
0 101 110010 10001100101000 1011001101111010111011110101001101111000000000000110001100000100111110100010101 101010111111101001000101110110100000111011011011110111100110100100000100100001111101101110011101000101110110001101101000100100100110000111001010101011110010001111100011110100010101011011111111000110101110111100001011100111110000000010101100110101001010001001001011000000110000010010010100010010000001110100101000011111001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Ring
see "Number to convert : "
give a
n = 0
while pow(2,n+1) < a
n = n + 1
end
for i = n to 0 step -1
x = pow(2,i)
if a >= x see 1 a = a - x
else see 0 ok
next
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))
RPL
RPL handles both floating point numbers and binary integers, but the latter are visualized with a #
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. DEC
, HEX
, OCT
or BIN
.
To comply with the task, we have just to remove these characters.
≪ BIN R→B →STR 3 OVER SIZE 1 - SUB ≫ '→PLNB' STO
- Input:
5 →PLNB 50 →PLNB 9000 →PLNB
- Output:
3: "101" 2: "110010" 1: "10001100101000"
Ruby
[5,50,9000].each do |n|
puts "%b" % n
end
or
for n in [5,50,9000]
puts n.to_s(2)
end
- Output:
101 110010 10001100101000
Run BASIC
input "Number to convert:";a
while 2^(n+1) < a
n = n + 1
wend
for i = n to 0 step -1
x = 2^i
if a >= x then
print 1;
a = a - x
else
print 0;
end if
next
- Output:
Number to convert:?9000 10001100101000
Rust
fn main() {
for i in 0..8 {
println!("{:b}", i)
}
}
Outputs:
0 1 10 11 100 101 110 111
S-lang
define int_to_bin(d)
{
variable m = 0x40000000, prn = 0, bs = "";
do {
if (d & m) {
bs += "1";
prn = 1;
}
else if (prn)
bs += "0";
m = m shr 1;
} while (m);
if (bs == "") bs = "0";
return bs;
}
() = printf("%s\n", int_to_bin(5));
() = printf("%s\n", int_to_bin(50));
() = printf("%s\n", int_to_bin(9000));
- Output:
101 110010 10001100101000
S-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
- Output:
5 = 101 50 = 110010 9000 = 10001100101000
Scala
Scala has an implicit conversion from Int
to RichInt
which has a method toBinaryString
.
scala> (5 toBinaryString)
res0: String = 101
scala> (50 toBinaryString)
res1: String = 110010
scala> (9000 toBinaryString)
res2: String = 10001100101000
Scheme
(display (number->string 5 2)) (newline)
(display (number->string 50 2)) (newline)
(display (number->string 9000 2)) (newline)
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/
- Output:
$ 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
Seed7
This example uses the radix operator to write a number in binary.
$ include "seed7_05.s7i";
const proc: main is func
local
var integer: number is 0;
begin
for number range 0 to 16 do
writeln(number radix 2);
end for;
end func;
- Output:
0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 10000
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;
- Output:
101 110010 10001100101000
SequenceL
main := toBinaryString([5, 50, 9000]);
toBinaryString(number(0)) :=
let
val := "1" when number mod 2 = 1 else "0";
in
toBinaryString(floor(number/2)) ++ val when floor(number/2) > 0
else
val;
- Output:
["101","110010","10001100101000"]
Sidef
[5, 50, 9000].each { |n|
say n.as_bin;
}
- Output:
101 110010 10001100101000
Simula
BEGIN
PROCEDURE OUTINTBIN(N); INTEGER N;
BEGIN
IF N > 1 THEN OUTINTBIN(N//2);
OUTINT(MOD(N,2),1);
END OUTINTBIN;
INTEGER SAMPLE;
FOR SAMPLE := 5, 50, 9000 DO BEGIN
OUTINTBIN(SAMPLE);
OUTIMAGE;
END;
END
- Output:
101 110010 10001100101000
SkookumScript
println(5.binary)
println(50.binary)
println(9000.binary)
Or looping over a list of numbers:
{5 50 9000}.do[println(item.binary)]
- Output:
101 110010 10001100101000
Smalltalk
5 printOn: Stdout radix:2
50 printOn: Stdout radix:2
9000 printOn: Stdout radix:2
or:
#(5 50 9000) do:[:each | each printOn: Stdout radix:2. Stdout cr]
SNOBOL4
define('bin(n,r)') :(bin_end)
bin bin = le(n,0) r :s(return)
bin = bin(n / 2, REMDR(n,2) r) :(return)
bin_end
output = bin(5)
output = bin(50)
output = bin(9000)
end
- Output:
101 110010 10001100101000
SNUSP
/recurse\
$,binary!\@\>?!\@/<@\.#
! \=/ \=itoa=@@@+@+++++#
/<+>- \ div2
\?!#-?/+# mod2
Standard ML
print (Int.fmt StringCvt.BIN 5 ^ "\n");
print (Int.fmt StringCvt.BIN 50 ^ "\n");
print (Int.fmt StringCvt.BIN 9000 ^ "\n");
Swift
for num in [5, 50, 9000] {
println(String(num, radix: 2))
}
- Output:
101 110010 10001100101000
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"
}
Demonstrating:
for {set x 0} {$x < 16} {incr x} {
puts [num2bin $x]
}
puts "--------------"
puts [num2bin 5]
puts [num2bin 50]
puts [num2bin 9000]
- Output:
0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 -------------- 101 110010 10001100101000
Or you can use the builtin format:
foreach n {0 1 5 50 9000} {
puts [format "%4u: %b" $n $n]
}
- Output:
0: 0 1: 1 5: 101 50: 110010 9000: 10001100101000
TI-83 BASIC
Using Standard TI-83 BASIC
PROGRAM:BINARY
:Disp "NUMBER TO"
:Disp "CONVERT:"
:Input A
:0→N
:0→B
:While 2^(N+1)≤A
:N+1→N
:End
:While N≥0
:iPart(A/2^N)→C
:10^(N)*C+B→B
:If C=1
:Then
:A-2^N→A
:End
:N-1→N
:End
:Disp B
Alternate using a string to display larger numbers.
PROGRAM:BINARY
:Input X
:" "→Str1
:Repeat X=0
:X/2→X
:sub("01",2fPart(X)+1,1)+Str1→Str1
:iPart(X)→X
:End
:Str1
Using the baseInput() "real(25," function from Omnicalc
PROGRAM:BINARY
:Disp "NUMBER TO"
:Disp "CONVERT"
:Input "Str1"
:Disp real(25,Str1,10,2)
More compact version:
:Input "DEC: ",D
:" →Str1
:If not(D:"0→Str1
:While D>0
:If not(fPart(D/2:Then
:"0"+Str1→Str1
:Else
:"1"+Str1→Str1
:End
:iPart(D/2→D
:End
:Disp Str1
uBasic/4tH
This will convert any decimal number to any base between 2 and 16.
Do
Input "Enter base (1<X<17): "; b
While (b < 2) + (b > 16)
Loop
Input "Enter number: "; n
s = (n < 0) ' save the sign
n = Abs(n) ' make number unsigned
For x = 0 Step 1 Until n = 0 ' calculate all the digits
@(x) = n % b
n = n / b
Next x
If s Then Print "-"; ' reapply the sign
For y = x - 1 To 0 Step -1 ' print all the digits
If @(y) > 9 Then ' take care of hexadecimal digits
Gosub @(y) * 10
Else
Print @(y); ' print "decimal" digits
Endif
Next y
Print ' finish the string
End
100 Print "A"; : Return ' print hexadecimal digit
110 Print "B"; : Return
120 Print "C"; : Return
130 Print "D"; : Return
140 Print "E"; : Return
150 Print "F"; : Return
- Output:
Enter base (1<X<17): 2 Enter number: 9000 10001100101000 0 OK, 0:775
Uiua
PrintBits ← &p/$"__"⇌⋯
≡PrintBits 5_50_9000
- Output:
stdout: 101 110010 10001100101000
UNIX Shell
Since POSIX does not specify local variables, make use of set
for highest portability.
bin() {
set -- "${1:-0}" ""
while [ 1 -lt "$1" ]
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)
- Output:
0 1 10 101 110010 10001100101000
VBA
2 ways :
1- Function DecToBin(ByVal Number As Long) As String
Arguments :
[Required] Number (Long) : should be a positive number
2- Function DecToBin2(ByVal Number As Long, Optional Places As Long) As String
Arguments :
[Required] Number (Long) : should be >= -512 And <= 511
[Optional] Places (Long) : the number of characters to use.
Note : If places is omitted, DecToBin2 uses the minimum number of characters necessary. Places is useful for padding the return value with leading 0s (zeros).
Option Explicit
Sub Main_Dec2bin()
Dim Nb As Long
Nb = 5
Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin(Nb)
Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin2(Nb)
Nb = 50
Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin(Nb)
Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin2(Nb)
Nb = 9000
Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin(Nb)
Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin2(Nb)
End Sub
Function DecToBin(ByVal Number As Long) As String
Dim strTemp As String
Do While Number > 1
strTemp = Number - 2 * (Number \ 2) & strTemp
Number = Number \ 2
Loop
DecToBin = Number & strTemp
End Function
Function DecToBin2(ByVal Number As Long, Optional Places As Long) As String
If Number > 511 Then
DecToBin2 = "Error : Number is too large ! (Number must be < 511)"
ElseIf Number < -512 Then
DecToBin2 = "Error : Number is too small ! (Number must be > -512)"
Else
If Places = 0 Then
DecToBin2 = WorksheetFunction.Dec2Bin(Number)
Else
DecToBin2 = WorksheetFunction.Dec2Bin(Number, Places)
End If
End If
End Function
- Output:
The decimal value 5 should produce an output of : 101 The decimal value 5 should produce an output of : 101 The decimal value 50 should produce an output of : 110010 The decimal value 50 should produce an output of : 110010 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)
Vedit macro language
This implementation reads the numeric values from user input and writes the converted binary values in the edit buffer.
repeat (ALL) {
#10 = Get_Num("Give a numeric value, -1 to end: ", STATLINE)
if (#10 < 0) { break }
Call("BINARY")
Update()
}
return
:BINARY:
do {
Num_Ins(#10 & 1, LEFT+NOCR)
#10 = #10 >> 1
Char(-1)
} while (#10 > 0)
EOL
Ins_Newline
Return
Example output when values 0, 1, 5, 50 and 9000 were entered:
0 1 101 110010 10001100101000
Vim Script
function Num2Bin(n)
let n = a:n
let s = ""
if n == 0
let s = "0"
else
while n
if n % 2 == 0
let s = "0" . s
else
let s = "1" . s
endif
let n = n / 2
endwhile
endif
return s
endfunction
echo Num2Bin(5)
echo Num2Bin(50)
echo Num2Bin(9000)
- Output:
101 110010 10001100101000
Visual Basic
Public Function Bin(ByVal l As Long) As String
Dim i As Long
If l Then
If l And &H80000000 Then 'negative number
Bin = "1" & String$(31, "0")
l = l And (Not &H80000000)
For i = 0 To 30
If l And (2& ^ i) Then
Mid$(Bin, Len(Bin) - i) = "1"
End If
Next i
Else 'positive number
Do While l
If l Mod 2 Then
Bin = "1" & Bin
Else
Bin = "0" & Bin
End If
l = l \ 2
Loop
End If
Else
Bin = "0" 'zero
End If
End Function
'testing:
Public Sub Main()
Debug.Print Bin(5)
Debug.Print Bin(50)
Debug.Print Bin(9000)
End Sub
- Output:
101 110010 10001100101000
Visual Basic .NET
Module Program
Sub Main
For Each number In {5, 50, 9000}
Console.WriteLine(Convert.ToString(number, 2))
Next
End Sub
End Module
- Output:
101 110010 10001100101000
Visual FoxPro
*!* Binary Digits
CLEAR
k = CAST(5 As I)
? NToBin(k)
k = CAST(50 As I)
? NToBin(k)
k = CAST(9000 As I)
? NToBin(k)
FUNCTION NTOBin(n As Integer) As String
LOCAL i As Integer, b As String, v As Integer
b = ""
v = HiBit(n)
FOR i = 0 TO v
b = IIF(BITTEST(n, i), "1", "0") + b
ENDFOR
RETURN b
ENDFUNC
FUNCTION HiBit(n As Double) As Integer
*!* Find the highest power of 2 in n
LOCAL v As Double
v = LOG(n)/LOG(2)
RETURN FLOOR(v)
ENDFUNC
- Output:
101 110010 10001100101000
V (Vlang)
fn main() {
for i in 0..16 {
println("${i:b}")
}
}
- Output:
0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111
VTL-2
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 #=;
- Output:
101 110010 10001100101000
VBScript
Using no Math....
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)
- Output:
101 110010 10001100101000
Whitespace
This program prints binary numbers until the internal representation of the current integer overflows to -1; it will never do so on some interpreters. It is almost an exact duplicate of Count in octal#Whitespace.
It was generated from the following pseudo-Assembly.
push 0
; Increment indefinitely.
0:
push -1 ; Sentinel value so the printer knows when to stop.
copy 1
call 1
push 10
ochr
push 1
add
jump 0
; Get the binary digits on the stack in reverse order.
1:
dup
push 2
mod
swap
push 2
div
push 0
copy 1
sub
jn 1
pop
; Print them.
2:
dup
jn 3 ; Stop at the sentinel.
onum
jump 2
3:
pop
ret
Wortel
Using JavaScripts buildin toString method on the Number object, the following function takes a number and returns a string with the binary representation:
\.toString 2
; the following function also casts the string to a number
^(@+ \.toString 2)
To output to the console:
@each ^(console.log \.toString 2) [5 50 900]
Outputs:
101 110010 1110000100
Wren
import "./fmt" for Fmt
System.print("Converting to binary:")
for (i in [5, 50, 9000]) Fmt.print("$d -> $b", i, i)
- Output:
Converting to binary: 5 -> 101 50 -> 110010 9000 -> 10001100101000
X86 Assembly
Translation of XPL0. Assemble with tasm, tlink /t
.model tiny
.code
.486
org 100h
start: mov ax, 5
call binout
call crlf
mov ax, 50
call binout
call crlf
mov ax, 9000
call binout
crlf: mov al, 0Dh ;new line
int 29h
mov al, 0Ah
int 29h
ret
binout: push ax
shr ax, 1
je bo10
call binout
bo10: pop ax
and al, 01h
or al, '0'
int 29h ;display character
ret
end start
- Output:
101 110010 10001100101000
x86-64 Assembly
FASM direct to executable (FreeBSD format):
format ELF64 executable 9
segment readable
nums: dd 5, 50, 9000, 0 ;numbers to convert, 0 as end of data indicator
segment readable writable
result: times 16 db 0 ;empty string for printing the result later
db 10, 0
segment readable executable
entry start
start:
xor rbx, rbx ;index for nums
mov eax, [nums + 4 * rbx]
mov rcx, 16 ;index for result string
convert:
dec rcx
mov rdi, 1 ;get least significant bit
and rdi, rax
add rdi, '0' ;convert to char
mov [result + rcx], dil ;and put it in result[ecx]
shr rax, 1 ;right shift, 1 bit
test rax, rax ;eax still > 0
jnz convert ;if yes, repeat
mov rax, 4 ;print result
mov rdi, 1
mov rsi, result
mov rdx, 18
syscall
xor rax, rax ;reset string to 0s (not strictly needed,
mov [result], rax ;because we have increasing numbers, and
mov [result + 8], rax ;old chars will be overwritten)
inc rbx ;and repeat if list isn't done
mov eax, [nums + 4 * rbx]
mov rcx, 16
test rax, rax
jnz convert
mov rax, 1 ;exit
xor rdi, rdi
syscall
- Output:
101 110010 10001100101000
NASM syntax. Numbers passed from the command line. By changing the outbase constant, any base from 2 to 16 can be converted.
global _start
bsize equ 72
outbase equ 2 ; 2 to 16
section .text
_start:
pop rcx
dec rcx
or rcx, rcx
jz .exit0
pop rdx
xor rdx, rdx
.cmdloop:
pop rdi
call atoq
mov qword [slot + rdx * 8], rax
inc rdx
cmp rdx, rcx
jne .cmdloop
xor rdx, rdx
.printloop:
mov rdi, qword [slot + rdx * 8]
call printq
inc rdx
cmp rdx, rcx
jne .printloop
.exit0:
mov rax, 60
mov rdi, 0
syscall
atoq:
push r8
push r9
push rdi
push rsi
push rdx
push rcx
xor rcx, rcx
xor rax, rax
xor r8, r8
mov r9, 1
cmp byte[rdi], 0
jz .exit
cmp byte[rdi], '-'
jne .stbegin
mov r9, -1
inc rdi
.stbegin:
cmp byte[rdi], '0'
jl .return
cmp byte[rdi], '9'
jg .return
.stloop:
cmp byte[rdi + r8], '0'
jl .calc0
cmp byte[rdi + r8], '9'
jg .calc0
mov sil, byte[rdi + r8]
sub rsi, '0'
push rsi
inc r8
jmp .stloop
.calc0:
xor rcx, rcx
mov rdi, 10
mov rsi, 1
.calc1:
pop rax
mul rsi
add rcx, rax
dec r8
jz .return
mov rax, rsi
mul rdi
mov rsi, rax
jmp .calc1
.return:
xor rdx, rdx
mov rax, rcx
imul r9
.exit:
pop rcx
pop rdx
pop rsi
pop rdi
pop r9
pop r8
ret
printq:
push r9
push rdi
push rsi
push rdx
push rcx
push rax
mov rax, rdi
mov r9, bsize
dec r9
mov rsi, outbase
sub rsp, bsize
sub rax, 0
jns .stloop
neg rax
.stloop:
xor rdx, rdx
div rsi
mov dl, byte [charset + rdx]
mov byte[rsp + r9], dl
sub rax, 0
jz .negtest
dec r9
jmp .stloop
.negtest:
sub rdi, 0
jns .printit
dec r9
mov byte[rsp + r9], '-'
.printit:
mov rdx, bsize
sub rdx, r9
mov rsi, rsp
add rsi, r9
mov rdi, 1
mov rax, 1
syscall
mov rsi, 0x0a
push rsi
mov rsi, rsp
mov rdx, 1
mov rax, 1
mov rdi, 1
syscall
pop rsi
.restores:
add rsp, bsize
pop rax
pop rcx
pop rdx
pop rsi
pop rdi
pop r9
.return:
ret
section .data
charset: db "0123456789abcdef"
section .bss
slot: resq 16
- Output:
$ nasm dec2bin.asm -o dec2bin.o -f elf64 $ ld dec2bin.o -o dec2bin -s -z noexecstack -no-pie $ ./dec2bin 5 50 9000 101 110010 10001100101000 $
Same source code with outbase changed from 2 to 16.
$ nasm dec2bin.asm -o dec2hex.o -f elf64 $ ld dec2hex.o -o dec2hex -s -z noexecstack -no-pie $ ./dec2hex 5 50 9000 255 5 32 2328 ff $
XPL0
include c:\cxpl\codes; \intrinsic code declarations
proc BinOut(N); \Output N in binary
int N;
int R;
[R:= N&1;
N:= N>>1;
if N then BinOut(N);
ChOut(0, R+^0);
];
int I;
[I:= 0;
repeat BinOut(I); CrLf(0);
I:= I+1;
until KeyHit or I=0;
]
- Output:
0 1 10 11 100 101 110 111 1000 ... 100000010011110 100000010011111 100000010100000 100000010100001
Yabasic
dim a(3)
a(0) = 5
a(1) = 50
a(2) = 9000
for i = 0 to 2
print a(i) using "####", " -> ", bin$(a(i))
next i
end
Z80 Assembly
org &8000
PrintChar equ &BB5A ;syscall - prints accumulator to Amstrad CPC's screen
main:
ld hl,TestData0
call PrintBinary_NoLeadingZeroes
ld hl,TestData1
call PrintBinary_NoLeadingZeroes
ld hl,TestData2
call PrintBinary_NoLeadingZeroes
ret
TestData0:
byte 5,255
TestData1:
byte 5,0,255
TestData2:
byte 9,0,0,0,255
temp:
byte 0
;temp storage for the accumulator
; we can't use the stack to preserve A since that would also preserve the flags.
PrintBinary_NoLeadingZeroes:
;setup:
ld bc,&8000 ;B is the revolving bit mask, C is the "have we seen a zero yet" flag
NextDigit:
ld a,(hl)
inc hl
cp 255
jp z,Terminated
ld (temp),a
NextBit:
ld a,(temp)
and b
jr z,PrintZero
; else, print one
ld a,'1' ;&31
call &BB5A
set 0,b ;bit 0 of B is now 1, so we can print zeroes now.
jr Predicate
PrintZero:
ld a,b
or a
jr z,Predicate ;if we haven't seen a zero yet, don't print a zero.
ld a,'0' ;&30
call &BB5A
Predicate:
rrc b
;rotate the mask right by one. If it sets the carry,
; it's back at the start, and we need to load the next byte.
jr nc,NextBit
jr NextDigit ;back to top
Terminated:
ld a,13
call &BB5A
ld a,10
jp &BB5A ;its ret will return for us.
This is another version. Output of the result over port 0A hex.
; HL contains the value to be converted
ld hl,5
call binary
ld hl,50
call binary
ld hl,9000
call binary
halt
; Convert to binary
; The OUT(0x0A),A command does the output to an device
binary: push hl
push bc
ld c,0x00
call gobin
ld h,l
call gobin
pop bc
pop hl
ret
gobin: ld b,0x08
bitloop: ld a,h
bit 7,h
jr nz,one
zero: ld a,c
or a
jr z,end1
ld a,"0"
out (0x0a),a
jr end1
one: ld a,"1"
ld c,0x01
out (0x0a),a
end1: ld a,h
rlca
ld h,a
djnz bitloop
ret
zkl
(9000).toString(2)
T(5,50,9000).apply("toString",2) //--> L("101","110010","10001100101000")
"%.2B".fmt(9000)
ZX Spectrum Basic
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$
999 STOP
1000 REM convert to binary
1010 LET t=n: REM temporary variable
1020 LET s$="": REM this will contain our binary digits
1030 LET sf=0: REM output has not started yet
1040 FOR l=126 TO 0 STEP -1
1050 LET d$="0": REM assume next digit is zero
1060 IF t>=(2^l) THEN LET d$="1": LET t=t-(2^l): LET sf=1
1070 IF (sf <> 0) THEN LET s$=s$+d$
1080 NEXT l
1090 RETURN
- Radices
- Programming Tasks
- Basic language learning
- 8th
- 11l
- 360 Assembly
- 0815
- 6502 Assembly
- 8080 Assembly
- 8086 Assembly
- AArch64 Assembly
- ACL2
- Action!
- Ada
- Aime
- ALGOL 68
- ALGOL W
- ALGOL-M
- APL
- AppleScript
- ARM Assembly
- Arturo
- AutoHotkey
- AutoIt
- AWK
- Axe
- BaCon
- Bash
- BASIC
- Applesoft BASIC
- BASIC256
- BBC BASIC
- CBASIC
- Chipmunk Basic
- Commodore BASIC
- IS-BASIC
- QBasic
- Tiny BASIC
- True BASIC
- XBasic
- Batch File
- Bc
- BCPL
- Beads
- Befunge
- BQN
- Bracmat
- Brainf***
- Burlesque
- C
- C sharp
- C++
- Ceylon
- Clojure
- CLU
- COBOL
- CoffeeScript
- Common Lisp
- Component Pascal
- Cowgol
- Crystal
- D
- Dart
- Dc
- Delphi
- Draco
- DuckDB
- Dt
- Dyalect
- EasyLang
- EchoLisp
- Ecstasy
- Ed
- Elena
- Elixir
- Emacs Lisp
- Epoxy
- Erlang
- Euphoria
- F Sharp
- Factor
- FALSE
- FBSL
- FOCAL
- Forth
- Fortran
- Free Pascal
- FreeBASIC
- Frink
- FunL
- Futhark
- FutureBasic
- Gambas
- Go
- Groovy
- Haskell
- Icon
- Unicon
- Idris
- J
- Java
- JavaScript
- Joy
- Jq
- Julia
- K
- Kotlin
- Ksh
- Lambdatalk
- Lang
- Lang5
- LFE
- Liberty BASIC
- Little Man Computer
- LLVM
- Locomotive Basic
- LOLCODE
- LSL
- Lua
- M2000 Interpreter
- MACRO-11
- MAD
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Octave
- Maxima
- MAXScript
- Mercury
- Min
- MiniScript
- MLite
- Modula-2
- Modula-3
- NetRexx
- NewLisp
- Nickle
- Nim
- Nu
- Oberon-2
- Objeck
- OCaml
- Oforth
- Ol
- OxygenBasic
- Panda
- PARI/GP
- Pascal
- PascalABC.NET
- Peloton
- Perl
- Phix
- Phixmonti
- PHP
- Picat
- PicoLisp
- Piet
- PL/I
- PL/M
- PowerBASIC
- PowerShell
- Microsoft .NET Framework
- Processing
- Prolog
- PureBasic
- Python
- QB64
- Quackery
- R
- Racket
- Raku
- RapidQ
- Red
- Retro
- Refal
- REXX
- Ring
- Roc
- RPL
- Ruby
- Run BASIC
- Rust
- S-lang
- S-BASIC
- Scala
- Scheme
- Sed
- Seed7
- SETL
- SequenceL
- Sidef
- Simula
- SkookumScript
- Smalltalk
- SNOBOL4
- SNUSP
- Standard ML
- Swift
- Tcl
- TI-83 BASIC
- UBasic/4tH
- Uiua
- UNIX Shell
- VBA
- Vedit macro language
- Vim Script
- Visual Basic
- Visual Basic .NET
- Visual FoxPro
- V (Vlang)
- VTL-2
- VBScript
- Whitespace
- Wortel
- Wren
- Wren-fmt
- X86 Assembly
- X86-64 Assembly
- XPL0
- Yabasic
- Z80 Assembly
- Zkl
- ZX Spectrum Basic
- Pages with too many expensive parser function calls