comparison scripts/strings/dec2bin.m @ 11172:7e8ce65f73cf

Overhaul functions used to convert between number bases.
author Rik <octave@nomad.inbox5.com>
date Sun, 31 Oct 2010 07:30:15 -0700
parents 693e22af08ae
children fd0a3ac60b0e
comparison
equal deleted inserted replaced
11171:bc3fa8f6c4dc 11172:7e8ce65f73cf
16 ## You should have received a copy of the GNU General Public License 16 ## You should have received a copy of the GNU General Public License
17 ## along with Octave; see the file COPYING. If not, see 17 ## along with Octave; see the file COPYING. If not, see
18 ## <http://www.gnu.org/licenses/>. 18 ## <http://www.gnu.org/licenses/>.
19 19
20 ## -*- texinfo -*- 20 ## -*- texinfo -*-
21 ## @deftypefn {Function File} {} dec2bin (@var{n}, @var{len}) 21 ## @deftypefn {Function File} {} dec2bin (@var{d}, @var{len})
22 ## Return a binary number corresponding to the non-negative decimal number 22 ## Return a binary number corresponding to the non-negative integer
23 ## @var{n}, as a string of ones and zeros. For example: 23 ## @var{d}, as a string of ones and zeros. For example:
24 ## 24 ##
25 ## @example 25 ## @example
26 ## @group 26 ## @group
27 ## dec2bin (14) 27 ## dec2bin (14)
28 ## @result{} "1110" 28 ## @result{} "1110"
29 ## @end group 29 ## @end group
30 ## @end example 30 ## @end example
31 ## 31 ##
32 ## If @var{n} is a vector, returns a string matrix, one row per value, 32 ## If @var{d} is a vector, returns a string matrix, one row per value,
33 ## padded with leading zeros to the width of the largest value. 33 ## padded with leading zeros to the width of the largest value.
34 ## 34 ##
35 ## The optional second argument, @var{len}, specifies the minimum 35 ## The optional second argument, @var{len}, specifies the minimum
36 ## number of digits in the result. 36 ## number of digits in the result.
37 ## @seealso{bin2dec, dec2base, base2dec, hex2dec, dec2hex} 37 ## @seealso{bin2dec, dec2base, dec2hex}
38 ## @end deftypefn 38 ## @end deftypefn
39 39
40 ## Author: Daniel Calvelo <dcalvelo@yahoo.com> 40 ## Author: Daniel Calvelo <dcalvelo@yahoo.com>
41 ## Adapted-by: Paul Kienzle <pkienzle@kienzle.powernet.co.uk> 41 ## Adapted-by: Paul Kienzle <pkienzle@kienzle.powernet.co.uk>
42 42
43 function retval = dec2bin (n, len) 43 function b = dec2bin (d, len)
44 44
45 if (nargin == 1) 45 if (nargin == 1)
46 retval = dec2base (n, 2); 46 b = dec2base (d, 2);
47 elseif (nargin == 2) 47 elseif (nargin == 2)
48 retval = dec2base (n, 2, len); 48 b = dec2base (d, 2, len);
49 else 49 else
50 print_usage (); 50 print_usage ();
51 endif 51 endif
52 52
53 endfunction 53 endfunction
54 54
55 %!assert(strcmp (dec2bin (14), "1110")); 55 %!assert(strcmp (dec2bin (14), "1110"));
56
57 %!error dec2bin ();
58
59 %!assert(strcmp (dec2bin (14, 6), "001110")); 56 %!assert(strcmp (dec2bin (14, 6), "001110"));
60 57
58 %%Test input validation
59 %!error dec2bin ();
61 %!error dec2bin (1, 2, 3); 60 %!error dec2bin (1, 2, 3);
62 61