]> Creatis software - CreaPhase.git/blob - octave_packages/m/strings/dec2bin.m
update packages
[CreaPhase.git] / octave_packages / m / strings / dec2bin.m
1 ## Copyright (C) 1996-2012 Daniel Calvelo
2 ##
3 ## This file is part of Octave.
4 ##
5 ## Octave is free software; you can redistribute it and/or modify it
6 ## under the terms of the GNU General Public License as published by
7 ## the Free Software Foundation; either version 3 of the License, or (at
8 ## your option) any later version.
9 ##
10 ## Octave is distributed in the hope that it will be useful, but
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 ## General Public License for more details.
14 ##
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING.  If not, see
17 ## <http://www.gnu.org/licenses/>.
18
19 ## -*- texinfo -*-
20 ## @deftypefn {Function File} {} dec2bin (@var{d}, @var{len})
21 ## Return a binary number corresponding to the non-negative integer
22 ## @var{d}, as a string of ones and zeros.  For example:
23 ##
24 ## @example
25 ## @group
26 ## dec2bin (14)
27 ##      @result{} "1110"
28 ## @end group
29 ## @end example
30 ##
31 ## If @var{d} is a matrix or cell array, return a string matrix with one
32 ## row per element in @var{d}, padded with leading zeros to the width of 
33 ## the largest value.
34 ##
35 ## The optional second argument, @var{len}, specifies the minimum
36 ## number of digits in the result.
37 ## @seealso{bin2dec, dec2base, dec2hex}
38 ## @end deftypefn
39
40 ## Author: Daniel Calvelo <dcalvelo@yahoo.com>
41 ## Adapted-by: Paul Kienzle <pkienzle@kienzle.powernet.co.uk>
42
43 function b = dec2bin (d, len)
44
45   if (nargin == 1)
46     b = dec2base (d, 2);
47   elseif (nargin == 2)
48     b = dec2base (d, 2, len);
49   else
50     print_usage ();
51   endif
52
53 endfunction
54
55
56 %!assert(dec2bin (14), "1110");
57 %!assert(dec2bin (14, 6), "001110");
58 %!assert(dec2bin ({1, 2; 3, 4}), ["001"; "011"; "010"; "100"]);
59
60 %%Test input validation
61 %!error dec2bin ();
62 %!error dec2bin (1, 2, 3);
63