function [ binary,decimal ] = num2binary16( number )

function [ binary,decimal ] = num2binary16( number )
%The IEEE 754 standard specifies a binary16 as having the following format:

%Sign bit: 1 bit
%Exponent width: 5 bits
%Significand precision: 11 bits (10 explicitly stored)
%S EEEEE MMMMMMMMMM
%INPUT: number is a random precision number

%OUTPUT : var binary is a 2's string of the binary16
%         var decimail is the value of the number in decimal

%Author :Yang Li .
%Email: yangli0534@gmail.com

%Data:20150126
if real(number) >= 2^14 
    error('beyond the maximum :-2^14--+2^24');
end

S=number<0 ;
E=0;
M=abs(number);
while(M>=2 || M<1 )
    if(M>=2)
     E=E+1;
     M=M/2;
    else
        E=E-1;
        M=M*2;
    end   
end
M=round((M-1)*2^10) ;

  number1=(-1)^S*(2^ E   )*(1+M/2^10);
% binary=strcat(num2str(S),num2str(E),num2str(M))
E =E+15;
binary=strcat(num2str(S),dec2bin(E,5), dec2bin(M,10)) ;

sReal=(str2num(binary(1)));

eReal =-15;
for i=2:6
    eReal=eReal+str2num(binary(i))*2^(6-i);
end   
%  eReal=eReal*(-1)^str2num(binary(2));
mReal = 0;
for i=7:16
    mReal=mReal+str2num(binary(i))*2^(16-i);
end
 
numberReal=(-1)^sReal*2^eReal*(1+mReal/2^10);
err=num2str(abs(number-numberReal));
decimal=numberReal;
% disp(['the origin data is : ',num2str(number)]);
% disp(['the float format is : ',binary]);
% disp(['so ,there is a error :',num2str(abs(number-numberReal))]);

end

上一篇:Python核心技术与实战——十三|Python中参数传递机制


下一篇:C# WinForm 技巧:COMBOBOX搜索提示