]> Creatis software - CreaPhase.git/blob - octave_packages/m/strings/bin2dec.m
update packages
[CreaPhase.git] / octave_packages / m / strings / bin2dec.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} {} bin2dec (@var{s})
21 ## Return the decimal number corresponding to the binary number represented
22 ## by the string @var{s}.  For example:
23 ##
24 ## @example
25 ## @group
26 ## bin2dec ("1110")
27 ##      @result{} 14
28 ## @end group
29 ## @end example
30 ##
31 ## Spaces are ignored during conversion and may be used to make the binary
32 ## number more readable.
33 ##
34 ## @example
35 ## @group
36 ## bin2dec ("1000 0001")
37 ##      @result{} 129
38 ## @end group
39 ## @end example
40 ##
41 ## If @var{s} is a string matrix, return a column vector with one converted
42 ## number per row of @var{s}; Invalid rows evaluate to NaN@.
43 ##
44 ## If @var{s} is a cell array of strings, return a column vector with one
45 ## converted number per cell element in @var{s}.
46 ## @seealso{dec2bin, base2dec, hex2dec}
47 ## @end deftypefn
48
49 ## Author: Daniel Calvelo <dcalvelo@yahoo.com>
50 ## Adapted-by: Paul Kienzle <pkienzle@kienzle.powernet.co.uk>
51
52 function d = bin2dec (s)
53
54   if (nargin != 1)
55     print_usage ();
56   endif
57
58   d = base2dec (s, 2);
59
60 endfunction
61
62
63 %!assert(bin2dec ("0000"), 0);
64 %!assert(bin2dec ("1110"), 14);
65 %!assert(bin2dec ("11111111111111111111111111111111111111111111111111111"), 2^53-1);
66 %!assert(bin2dec ({"1110", "1111"}), [14; 15]);
67 %!assert (bin2dec ("1 0 1"), 5)
68 %!assert (bin2dec (char ("1 0 1", "   1111")), [5; 15]);
69
70 %%Test input validation
71 %!error bin2dec ();
72 %!error bin2dec (1);
73 %!error bin2dec ("1", 2);
74