Binary digits
The task is to output the sequence of binary digits for a given non negative decimal integer.
The decimal value 5, should produce an output of 101 The decimal value 50 should produce an out of 110010 The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using builtin radix functions within the language, if these are available, or alternatively a user defined function can be utilized. 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 superfluous leading zeros should not appear in the results.
AWK
<lang awk>BEGIN {
print tobinary(5) print tobinary(50) print tobinary(9000)
}
function tobinary(num) {
outstr = "" l = num while ( l ) { if ( l%2 == 0 ) { outstr = "0" outstr } else { outstr = "1" outstr } l = int(l/2) } return outstr
}</lang>
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.
<lang Icon>procedure main() every i := 5 | 50 | 255 | 1285 | 9000 do
write(i," = ",binary(i))
end
procedure binary(n) #: return bitstring for integer n static CT, cm, cb initial {
CT := table() # cache table for results cm := 2 ^ (cb := 4) # (tunable) cache modulus & pad bits }
b := "" # build reversed bit string while n > 0 do { # use cached result ...
if not (b ||:= \CT[1(i := n % cm, n /:= cm) ]) then { CT[j := i] := "" # ...or start new cache entry while j > 0 do CT[i] ||:= "01"[ 1(1+j % 2, j /:= 2 )] b ||:= CT[i] := left(CT[i],cb,"0") # finish cache with padding } }
return reverse(trim(b,"0")) # nothing extraneous end</lang>
Output:
5 = 101 50 = 110010 255 = 11111111 1285 = 10100000101 9000 = 10001100101000
J
<lang j> tobin=: -.&' '@":@#:
tobin 5
101
tobin 50
110010
tobin 9000
10001100101000</lang>
Algorithm: Remove spaces from the character list which results from formatting the binary list which represents the numeric argument.
I am using implicit output.
Java
<lang java>public class Main {
public static void main(String[] args) { System.out.println(Integer.toBinaryString(5)); System.out.println(Integer.toBinaryString(50)); System.out.println(Integer.toBinaryString(9000)); }
}</lang> Output:
101 110010 10001100101000
OCaml
<lang ocaml>let bin_of_int d =
if d < 0 then invalid_arg "bin_of_int" else if d = 0 then "0" else let rec aux acc d = if d = 0 then acc else let bit = (d land 1) = 1 in aux (bit::acc) (d lsr 1) in let bits = Array.of_list (aux [] d) in let str = String.create (Array.length bits) in Array.iteri (fun i bit -> str.[i] <- (if bit then '1' else '0')) bits; str
let () =
let d = read_int () in Printf.printf "%8s\n" (bin_of_int d)</lang>
PARI/GP
<lang parigp>bin(n:int)=concat(apply(s->Str(s),binary(n)))</lang>
PHP
<lang php><?php echo decbin(5); echo decbin(50); echo decbin(9000);</lang> Output:
101 110010 10001100101000
PicoLisp
<lang PicoLisp>: (bin 5) -> "101"
- (bin 50)
-> "110010"
- (bin 9000)
-> "10001100101000"</lang>
PureBasic
<lang 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</lang> Sample output:
101 110010 10001100101000
Python
<lang python>>>> 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</lang>
Tcl
<lang tcl>proc num2bin num {
# Convert to _fixed width_ big-endian 32-bit binary binary scan [binary format "I" $num] "B*" binval # Strip useless leading zeros by reinterpreting as a big decimal integer scan $binval "%lld"
}</lang> Demonstrating: <lang tcl>for {set x 0} {$x < 16} {incr x} {
puts [num2bin $x]
} puts "--------------" puts [num2bin 5] puts [num2bin 50] puts [num2bin 9000]</lang> Output:
0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 -------------- 101 110010 10001100101000
ZX Spectrum Basic
<lang 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</lang>