
function varargout = decode_ieee( d )
%DECODE_IEEE   Decodes an IEEE 754 double-precision value.
%   [S, E, M] = DECODE_IEEE(D) extracts the sign, exponent, and significand of D
%   such that D = S * M * 2^E.
%
% Pedro Gonnet, Oct 2010.
% Nick Hale, Oct 2013.

    % Return an error if somehow we have not received a double:
    if ( ~isa( d , 'double' ) )
        error('decode_ieee can only deal with inputs of type double.');
    end

    % Convert to binary string (lo and hi since ints are 32-bit):
    h = num2hex( d );
    hi = h(1:8); 
    lo = h(9:16);
    b = [ dec2bin( hex2dec( hi ) , 32 ) , dec2bin( hex2dec( lo ) , 32 ) ];
    
    % Select the sign, exp and mantissa (IEEE 754):
    s = b(1);
    e = b(2:12);
    m = b(13:64);
    
    % Display as binary values:
    ws = '                              ';
    fprintf('\n    %s|%s|%s\n    s      e%s m\n\n',s,e,m,ws);
    
    % Convert back to num:
    s = 1 - 2 * str2double(s);
    e = bin2dec(e) - 1023;
    m = bin2dec(m) / 2^52;
    
    % Add implicit first digit to m if normal number:
    if ( e > -1023 )
        m = m + 1.0; 
    end
    
    if ( nargout > 0 )
        varargout = {s, e, m};
    end
    
end
