########################################################################
##
## Copyright (C) 1996-2022 The Octave Project Developers
##
## See the file COPYRIGHT.md in the top-level directory of this
## distribution or <https://octave.org/copyright/>.
##
## This file is part of Octave.
##
## Octave is free software: you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## Octave is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Octave; see the file COPYING.  If not, see
## <https://www.gnu.org/licenses/>.
##
########################################################################

## -*- texinfo -*-
## @deftypefn  {} {} dec2bin (@var{d})
## @deftypefnx {} {} dec2bin (@var{d}, @var{len})
## Return a string of ones and zeros representing the conversion of the integer
## @var{d} to a binary number.
##
## If @var{d} is negative, return the two's complement binary value of @var{d}.
## If @var{d} is a matrix or cell d, return a string matrix with one row
## for each element in @var{d}, padded with leading zeros to the width of the
## largest value.
##
## The optional second argument, @var{len}, specifies the minimum number of
## digits in the result.
##
## Examples:
##
## @example
## @group
## dec2bin (14)
##      @result{} "1110"
##
## dec2bin (-14)
##      @result{} "11110010"
## @end group
## @end example
##
## Known @sc{matlab} Incompatibility: @sc{matlab}'s @code{dec2bin} allows
## non-integer values for @var{d}, truncating the value using the equivalent
## of @code{fix (@var{d})} for positive values, but, as of R2020b and in
## conflict with published documentation, appears to use
## @code{round (@var{d})} for negative values.  To be consistent with
## @code{dec2hex} and @code{dec2base}, Octave produces an error for non-integer
## valued inputs for @var{d}.  Users wanting compatible code for non-integer
## valued inputs should make use of @code{fix} or @code{round} as appropriate.
## @seealso{bin2dec, dec2base, dec2hex}
## @end deftypefn


function columnstr=dec2bin(d, len)

if (nargin == 0)
    print_usage ();
endif
if (iscell (d))
    d = cell2mat (d);
endif

outvec = struct('isneg', {}, 'str', {});
for i = d(:)'
  if ~isinteger(i) && ( i > flintmax(i) || i < -flintmax(i) )
    % Float magniture is too large to represent integers
    error('dec2bin: real inputs provided cannot accurately represent integers');
  end

  outvec(end+1).isneg = false;
  if i < 0 % Take 2-complement
    outvec(end).isneg = true;
    %len = len -1 % Reserve space for sign bit (TODO: could be wrong if user asked for less bits)
    % Add 1 first to be able to express it as a positive number without casting
    % The first conversion is in case i == flintmax
    i = uint64(-1*(int64(i)+1)); % Could be a type more adjusted to the size.
    % Anyway, once converting to binary representation, we'll just have to invert
  end

  if nargin == 1
    out = dec2base(i, 2);
  else
    out = dec2base(i, 2, len);
  end

  if outvec(end).isneg
    % The integer was negative, so we need to print the two-complemented value
    % invert bits
    out = char((out=='0') + '0');
    % Don't need an extra sign digit if output has a leading one
    if out(1) == '1'
      extra_char = 0;
    else
      extra_char = 1;
    end
    if nargin < 2 % Compute return length as closest to {8, 16, 32, 64}
      default_len = int8([8, 16, 32, 64]);
      len = default_len(find(idivide(default_len,length(out)+extra_char), 1));
    end
    if len<length(out)+extra_char % Min size to represent number, incl. sign bit
      len = length(out)+1;
    end
    % Add sign bit
    out = [char(ones(1,len-length(out))*'1'), out];
  endif
  outvec(end).str = out;
endfor

% Now a hack to pad shorter values with the correct sign bit
minlen = 0;
for st = outvec
  minlen = max(minlen, length(st.str));
end

columnstr = char(zeros(length(outvec), minlen));
for sti = 1:length(outvec)
  columnstr(sti,:) = [ ...
    char(ones(1,minlen-length(outvec(sti).str)).*('0'+outvec(sti).isneg)), ...
    outvec(sti).str];
end

end
%111111111111111111111111111111111111111111111111111111111111101
%!assert (dec2bin (3), "11")
%!assert (dec2bin (14), "1110")
%!assert (dec2bin (14, 6), "001110")
%!assert (dec2bin ([1, 2; 3, 4]), ["001"; "011"; "010"; "100"])
%!assert (dec2bin ({1, 2; 3, 4}), ["001"; "011"; "010"; "100"])
%!assert (dec2bin ({1, 2; 3, 4}, 4), ["0001"; "0011"; "0010"; "0100"])

## Test negative inputs
%!assert (dec2bin (-3), "11111101")
%#!assert (dec2bin (-3, 3), "11111101") % NOT SURE ABOUT MATLAB, BUT 101 IS A VALID ANSWER
%!assert (dec2bin (-2^7 -1), "1111111101111111")
%!assert (dec2bin (-2^15 -1), "11111111111111110111111111111111")
%!assert (dec2bin (-2^31 -1),
%!        "1111111111111111111111111111111101111111111111111111111111111111")
%!assert (dec2bin (-2^52),
%!        "1111111111110000000000000000000000000000000000000000000000000000")
%!test
%! assert (dec2bin (int64 (-2)^63),
%!        "1000000000000000000000000000000000000000000000000000000000000000");
%!test
%! assert (dec2bin (int64 (-2^63) -1),
%!        "1000000000000000000000000000000000000000000000000000000000000000");
%!test
%! assert (dec2bin (int64 (-2^63) +1),
%!        "1000000000000000000000000000000000000000000000000000000000000001");
%!assert (dec2bin ([-1, -2; -3, -4]),
%!        ["11111111"; "11111101"; "11111110"; "11111100"])
%!assert (dec2bin ([1, 2; 3, -4]),
%!        ["00000001"; "00000011"; "00000010"; "11111100"])
%!assert (dec2bin ({1, 2; 3, -4}),
%!        ["00000001"; "00000011"; "00000010"; "11111100"])

## Test basic functionality, output length, and bounds for 2-complement
%!assert (dec2bin(          0, 8), "00000000")
%!assert (dec2bin(uint8(   0), 8), '00000000')
%!assert (dec2bin( int8(   0)   ),        '0')
%!assert (dec2bin(uint8(   1), 8), '00000001')
%!assert (dec2bin(uint8(   1)   ),        '1')
%!assert (dec2bin(uint8(   2)   ),       '10')
%!assert (dec2bin( int8(   2)   ),       '10')
%!assert (dec2bin( int8( 126)   ),  '1111110')
%!assert (dec2bin(uint8( 126)   ),  '1111110')
%!assert (dec2bin( int8( 126), 8), '01111110')
%!assert (dec2bin(uint8( 126), 8), '01111110')
%!assert (dec2bin( int8( 127)   ),  '1111111')
%!assert (dec2bin(uint8( 127)   ),  '1111111')
%!assert (dec2bin( int8( 127), 8), '01111111')
%!assert (dec2bin(uint8( 127), 8), '01111111')
%!assert (dec2bin( int8(-128)   ), '10000000')
%!assert (dec2bin(uint8( 128)   ), '10000000')
%!assert (dec2bin( int8(-128), 8), '10000000')
%!assert (dec2bin(uint8( 128), 8), '10000000')
%!assert (dec2bin( int8(-127)   ), '10000001')
%!assert (dec2bin(uint8( 129)   ), '10000001')
%!assert (dec2bin( int8(-127), 8), '10000001')
%!assert (dec2bin(uint8( 129), 8), '10000001')
%!assert (dec2bin( int8(-126)   ), '10000010')
%!assert (dec2bin(uint8( 130)   ), '10000010')
%!assert (dec2bin( int8(  -2), 8), '11111110')
%!assert (dec2bin(uint8( 254)   ), '11111110')
%!assert (dec2bin( int8(  -1), 8), '11111111') % TODO: what does Matlab does when no len specified?
%!assert (dec2bin(uint8( 255)   ), '11111111')
%!assert (dec2bin(uint16( 2)^16   ), '1111111111111111') % Note: will saturate
%!assert (dec2bin( int16(-2)^15   ), '1000000000000000')
%!assert (dec2bin(uint32( 2)^32   ), '11111111111111111111111111111111')
%!assert (dec2bin( int32(-2)^31   ), '10000000000000000000000000000000')
%!assert (dec2bin(uint64( 2)^64   ), '1111111111111111111111111111111111111111111111111111111111111111')
%!assert (dec2bin( int64(-2)^63   ), '1000000000000000000000000000000000000000000000000000000000000000')
%!assert (dec2bin(intmin('int64')+10),'1000000000000000000000000000000000000000000000000000000000001010')

## Test input validation
%!error <Invalid call> dec2bin ()
%!error <dec2bin: real inputs provided cannot accurately represent integers> dec2bin (-2^63)
