function [b_out] = dec2bin(d_in, N)
% -------------------------------------------------------------------------
% MSc Project - MSc in Communications and Signal Processing
% Department of Electrical and Electronic Engineering
% Imperial College London, 2011
%
% Supervisor  : Dr Pier Luigi Dragotti
% Contributor : Andriy Gelman
% Author      : Jon Onativia Bravo
%
% File        : tree2bitstream.m
% -------------------------------------------------------------------------
% 
%
% [b_out] = dec2bin(d_in, N)
%
% INPUT:
%  - 
%
% OUTPUT:
%  - 
%

if nargin == 1
    max_pos = max([0 d_in]);
    max_neg = min([-1 d_in]);
    
    N_pos = ceil(log2(max_pos + 1) + 1);
    N_neg = ceil(log2(-max_neg) + 1);
    N     = max([N_pos, N_neg]);
end

b_out = false(1, N);

% Convert to two's complement
if d_in < 0
    d_in = 2^N + d_in;
end

b_idx = 1;
n     = N - 1;
while n >= 0
    b = false;
    if d_in >= 2^n
        b    = true;
        d_in = d_in - 2^n;
    end

    b_out(b_idx) = b;
    b_idx        = b_idx + 1;
    n            = n - 1;
end


end