IEEE 754 double precision machine numbers in Matlab

Download the files num2bin.m and bin2num.m (note that you have to put the files where Matlab can find them)

For a Matlab number x the command s=num2bin(x) gives a string of length 64 of zeros and ones containing the machine representation of x.

For a string s of length 64 consisting of ones and zeros the command x=bin2num(s) gives the corresponding number x.

According to the IEEE 754 standard, s(1) contains the sign, s(2:12) contains the exponent information, s(13:64) contains digits d2,...,d53 of the mantissa (for normalized numbers).

The exponent e is related to this by e = bin2dec(s(2:12))-1022 , or s(2:12) = dec2bin(e+1022,11)

Try this out with x = 1, 0.1, realmin, realmax, 0, -0, Inf, -Inf, NaN.

Examples

>> format long g % show all numbers with 15 digits
>> s='0000000000000000000000000000000000000000000000000000000000000001';
>> x=bin2num(s)
% the smallest positive (subnormal) machine number
x =
     4.94065645841247e-324
>> x = 1.4 ; s = num2bin(x)
% machine representation for x=1.4
s =
     0011111111110110011001100110011001100110011001100110011001100110
>> e = bin2dec(s(2:12)) - 1022
% find exponent e
e =
     1
>> s(13:64)
% find digits d2,...,d53 of mantissa. Remember that d1=1.
ans =
     0110011001100110011001100110011001100110011001100110
>> s(64) = '1'; x1 = bin2num(s)
% find next larger machine number x1 by increasing last bit of mantissa
x1 =
     1.4
>> x1 - x
% Matlab displays both x1 and x as 1.4. But x1 is a different machine number:
ans =
     2.22044604925031e-16
>> s(2:12) = dec2bin(-1 + 1022, 11); x2 = bin2num(s)
% change exponent to -1
x2 =
     0.35