1########################################################################
2##
3## Copyright (C) 1996-2021 The Octave Project Developers
4##
5## See the file COPYRIGHT.md in the top-level directory of this
6## distribution or <https://octave.org/copyright/>.
7##
8## This file is part of Octave.
9##
10## Octave is free software: you can redistribute it and/or modify it
11## under the terms of the GNU General Public License as published by
12## the Free Software Foundation, either version 3 of the License, or
13## (at your option) any later version.
14##
15## Octave is distributed in the hope that it will be useful, but
16## WITHOUT ANY WARRANTY; without even the implied warranty of
17## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18## GNU General Public License for more details.
19##
20## You should have received a copy of the GNU General Public License
21## along with Octave; see the file COPYING.  If not, see
22## <https://www.gnu.org/licenses/>.
23##
24########################################################################
25
26## -*- texinfo -*-
27## @deftypefn {} {} bin2dec (@var{s})
28## Return the decimal number corresponding to the binary number represented
29## by the string @var{s}.
30##
31## For example:
32##
33## @example
34## @group
35## bin2dec ("1110")
36##      @result{} 14
37## @end group
38## @end example
39##
40## Spaces are ignored during conversion and may be used to make the binary
41## number more readable.
42##
43## @example
44## @group
45## bin2dec ("1000 0001")
46##      @result{} 129
47## @end group
48## @end example
49##
50## If @var{s} is a string matrix, return a column vector with one converted
51## number per row of @var{s}; Invalid rows evaluate to NaN@.
52##
53## If @var{s} is a cell array of strings, return a column vector with one
54## converted number per cell element in @var{s}.
55## @seealso{dec2bin, base2dec, hex2dec}
56## @end deftypefn
57
58function d = bin2dec (s)
59
60  if (nargin != 1)
61    print_usage ();
62  endif
63
64  d = base2dec (s, 2);
65
66endfunction
67
68
69%!assert (bin2dec ("0000"), 0)
70%!assert (bin2dec ("1110"), 14)
71%!assert (bin2dec ("11111111111111111111111111111111111111111111111111111"), 2^53-1)
72%!assert (bin2dec ({"1110", "1111"}), [14; 15])
73%!assert (bin2dec ("1 0 1"), 5)
74%!assert (bin2dec (char ("1 0 1", "   1111")), [5; 15])
75
76## Test input validation
77%!error bin2dec ()
78%!error bin2dec (1)
79%!error bin2dec ("1", 2)
80