Binary digits: Difference between revisions

From Rosetta Code
Content added Content deleted
Line 39: Line 39:
Ada.Text_IO.Put_Line(To_Binary(9000)); -- 10001100101000
Ada.Text_IO.Put_Line(To_Binary(9000)); -- 10001100101000
end Binary_Output;</lang>
end Binary_Output;</lang>
=={{header|ALGOL 68}}==
{{works with|ALGOL 68|Revision 1.}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.3.3 algol68g-2.3.3].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to use of '''format'''[ted] ''transput''.}}

'''File: Binary_digits.a68'''<lang algol68>#!/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
))</lang>'''Output:'''
<pre style="height:15ex;overflow:scroll">
+5 => 101
+50 => 110010
+9000 => 10001100101000
+5 => TFT
+50 => TTFFTF
+9000 => TFFFTTFFTFTFFF

</pre>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==

Revision as of 13:26, 27 November 2011

Task
Binary digits
You are encouraged to solve this task according to the task description, using any language you may know.

The task is to output 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 builtin 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.

Ada

<lang Ada>with Ada.Text_IO;

procedure Binary_Output is

  package IIO is new Ada.Text_IO.Integer_IO(Integer);
  function To_Binary(N: Natural) return String is
     S: String(1 .. 1000); -- more than plenty!
     Left:  Positive := S'First;
     Right: Positive := S'Last;
  begin
     IIO.Put(To => S, Item => N, Base => 2); -- This is the conversion!
     -- Now S is a String with many spaces and some "2#...#" somewhere.
     -- We only need the "..." part without spaces or base markers.
     while S(Left) /= '#' loop
        Left := Left + 1;
     end loop;
     while S(Right) /= '#' loop
        Right := Right - 1;
     end loop;
     return S(Left+1 .. Right-1);
  end To_Binary;

begin

  Ada.Text_IO.Put_Line(To_Binary(5));    -- 101
  Ada.Text_IO.Put_Line(To_Binary(50));   -- 110010
  Ada.Text_IO.Put_Line(To_Binary(9000)); -- 10001100101000

end Binary_Output;</lang>

ALGOL 68

Works with: ALGOL 68 version Revision 1.
Works with: ALGOL 68G version Any - tested with release algol68g-2.3.3.


File: Binary_digits.a68<lang algol68>#!/usr/local/bin/a68g --script #

printf((

 $g" => "2r3d l$, 5, BIN 5,
 $g" => "2r6d l$, 50, BIN 50,
 $g" => "2r14d l$, 9000, BIN 9000

));

  1. 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

))</lang>Output:

         +5 => 101
        +50 => 110010
      +9000 => 10001100101000
         +5 => TFT
        +50 => TTFFTF
      +9000 => TFFFTTFFTFTFFF

AutoHotkey

<lang 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

}</lang>

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)
 }
 # Make sure we output a zero for a value of zero
 if ( outstr == "" ) {
   outstr = "0"
 }
 return outstr

}</lang>

bc

Translation of: dc

<lang bc>obase = 2 5 50 9000 quit</lang>

C

Converts int to a string. <lang c>#include <stdio.h>

void bin(int x, char *s) { char*_(int x){ *(s = x ? _(x >> 1) : s) = (x & 1) + '0'; return ++s; } *_(x) = 0; }

int main() { char a[100]; int i; for (i = 0; i <= 1984; i += 31) bin(i, a), printf("%4d: %s\n", i, a);

return 0; }</lang>

Common Lisp

Just print the number with "~b": <lang lisp>(format t "~b" 5)</lang>

C#

<lang csharp>using System;

class Program {

   static void Main()
   {
       foreach (var number in new[] { 5, 50, 9000 })
       {
           Console.WriteLine(Convert.ToString(number, 2));
       }
   }

}</lang> Output: <lang>101 110010 10001100101000</lang>

D

<lang d>import std.stdio;

void main() {

   foreach (i; 0 .. 16)
       writefln("%b", i);

}</lang>

Output:

0
1
10
11
100
101
110
111
1000
1001
1010
1011
1100
1101
1110
1111

Dart

<lang 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));

}</lang>

dc

<lang dc>2o 5p 50p 9000p</lang>

101
110010
10001100101000

Delphi

Units needed: SysUtils <lang Delphi>procedure Binary_Digits;

 function IntToBinStr(AInt : integer) : string;
 begin
   Result := ;
   while AInt > 0 do
     begin
       Result := Chr(Ord('0')+(AInt mod 2))+Result;
       AInt := AInt div 2;
     end;
 end;

begin

 writeln('   5: '+IntToBinStr(5));
 writeln('  50: '+IntToBinStr(50));
 writeln('9000: '+IntToBinStr(9000));

end;</lang>

   5: 101
  50: 110010
9000: 10001100101000

Erlang

<lang erlang>lists:map( fun(N) -> io:fwrite("~.2B~n", [N]) end, [5, 50, 9000]). </lang> Output:

101
110010
10001100101000

Euphoria

<lang 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')</lang>

Forth

<lang forth> 9000 50 5 2 base ! . . . decimal</lang>

Go

<lang go>package main

import ( "fmt" )

func main() { for i := 0; i < 16; i++ { fmt.Printf("%b\n", i) } }</lang>

Haskell

<lang haskell>import Data.List import Numeric import Text.Printf

-- Use the built-in function showIntAtBase. toBin n = showIntAtBase 2 ("01" !!) n ""

-- Implement our own version. toBin' 0 = "0" toBin' n = reverse $ unfoldr step n

 where step 0 = Nothing
       step m = let (d,r) = m `divMod` 2
                in Just ("01" !! r, d)

printToBin n = putStrLn $ printf "%4d %14s %14s" n (toBin n) (toBin' n)

main = do

 putStrLn $ printf "%4s  %14s  %14s" "N" "toBin" "toBin'"
 mapM_ printToBin [5, 50, 9000]</lang>

Sample output:

   N           toBin          toBin'
   5             101             101
  50          110010          110010
9000  10001100101000  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.

<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

JavaScript

<lang javascript>function toBinary(number) {

 return new Number(number).toString(2);

} var demoValues = [5, 50, 9000]; for (var i=0; i<demoValues.length; ++i) {

 print(toBinary(demoValues[i])); // alert() in a browser, wscript.echo in WSH, etc.

}</lang> Output:

101
110010
10001100101000

K

<lang k> tobin: ,/$2_vs

 tobin' 5 50 9000

("101"

"110010"
"10001100101000")</lang>

Locomotive Basic

<lang locobasic>10 PRINT BIN$(5) 20 PRINT BIN$(50) 30 PRINT BIN$(9000)</lang>

Output:

101
110010
10001100101000


Mathematica

<lang Mathematica>StringJoin @@ ToString /@ IntegerDigits[50, 2] </lang>

Modula-3

<lang modula3>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.</lang> Output:

1010
10010110

NetRexx

<lang NetRexx>/* NetRexx */

options replace format comments java crossref savelog symbols nobinary

nums = [5, 50, 9000]

loop n_ = 0 to nums.length - 1

 v_ = nums[n_]
 say v_.d2x.x2b.strip('L', 0)
 end n_

return </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
   aux (string_of_int (d land 1) :: acc) (d lsr 1)
 in
 String.concat "" (aux [] d)
 

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>

Pascal

See Delphi

Perl

<lang perl> for (5, 50, 9000) {

 printf "%b\n", $_;

}</lang>

101
110010
10001100101000

Perl 6

<lang perl6>say .fmt("%b") for 5, 50, 9000;</lang>

101
110010
10001100101000

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>

PL/I

Displays binary output, but with leading zeros: <lang PL/I>put list (25) (B);</lang>

Output: 0011001

With leading zero supression: <lang>

  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'));</lang>

Output: <lang> 11001 1111111111111111111111111111111 </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

Works with: Python version 3.X and 2.6+

<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>

Works with: Python version 3.X and 2.6+

<lang python>>>> for i in range(16): print(bin(i))

0b0 0b1 0b10 0b11 0b100 0b101 0b110 0b111 0b1000 0b1001 0b1010 0b1011 0b1100 0b1101 0b1110 0b1111</lang>

Pre-Python 2.6: <lang python>>>> oct2bin = {'0': '000', '1': '001', '2': '010', '3': '011', '4': '100', '5': '101', '6': '110', '7': '111'} >>> bin = lambda n: .join(oct2bin[octdigit] for octdigit in '%o' % n).lstrip('0') or '0' >>> for i in range(16): print(bin(i))

0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111</lang>

Retro

<lang Retro>9000 50 5 3 [ binary putn cr decimal ] times</lang>

REXX

<lang REXX>/* Rexx */ Do

 Queue 5
 Queue 50
 Queue 9000
 Do label n_ while queued() > 0
   Parse pull v_ .
   Say strip(x2b(d2x(v_)), 'L', '0')
   End n_
 Return

End Exit </lang>

Output
101
110010
10001100101000

Ruby

<lang ruby>[5,50,9000].each do |n|

 puts "%b" % n

end</lang> Output:

101
110010
10001100101000

Scala

<lang scala>5 toBinaryString // 101 50 toBinaryString // 110010 9000 toBinaryString // 10001100101000</lang>

Scheme

<lang scheme>(display (number->string 5 2)) (newline) (display (number->string 50 2)) (newline) (display (number->string 9000 2)) (newline)</lang>

Seed7

<lang seed7>$ include "seed7_05.s7i";

const proc: main is func

 local
   var integer: number is 0;
 begin
   for number range 0 to 16 do
     writeln(str(number, 2));
   end for;
 end func;</lang>

Output:

0
1
10
11
100
101
110
111
1000
1001
1010
1011
1100
1101
1110
1111
10000

Standard ML

<lang sml>print (Int.fmt StringCvt.BIN 5 ^ "\n"); print (Int.fmt StringCvt.BIN 50 ^ "\n"); print (Int.fmt StringCvt.BIN 9000 ^ "\n");</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

UNIX Shell

<lang sh># Define a function to output binary digits tobinary() {

 # We use the bench calculator for our conversion
 echo "obase=2;$1"|bc

}

  1. Call the function with each of our values

tobinary 5 tobinary 50</lang>

Visual Basic .NET

<lang vbnet> Sub Main()

   Console.WriteLine("5: " & Convert.ToString(5, 2))
   Console.WriteLine("50: " & Convert.ToString(50, 2))
   Console.WriteLine("9000: " & Convert.ToString(9000, 2))

End Sub </lang> Output:

5: 101
50: 110010
9000: 10001100101000

ZX Spectrum Basic

<lang zxbasic>10 LET n=5: GO SUB 1000: PRINT s$ 20 LET n=50: GO SUB 1000: PRINT s$ 30 LET n=9000: GO SUB 1000: PRINT s$ 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>