代码:
%% ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
%% Output Info about this m-file
fprintf('\n***********************************************************\n');
fprintf(' <DSP using MATLAB> Problem 6.24 \n\n'); banner();
%% ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
D = [1001, -63, -449, 978, -205]; fprintf('\nConvert a Sign-Magnitude Format Decimal integer D to its binary representation B! \n');
fprintf('\n %5d binary representation is :-- %20s -- \n', D(1), sm2bin(D(1)) );
fprintf('\n %5d binary representation is :-- %20s -- \n', D(2), sm2bin(D(2)) );
fprintf('\n %5d binary representation is :-- %20s -- \n', D(3), sm2bin(D(3)) );
fprintf('\n %5d binary representation is :-- %20s -- \n', D(4), sm2bin(D(4)) );
fprintf('\n %5d binary representation is :-- %20s -- \n', D(5), sm2bin(D(5)) ); %B = {'1010', '011011011', '11001', '1010101', '011011'};
%B = char('1010', '011011011', '11001', '1010101', '011011');
%B = ['1010'; '011011011'; '11001'; '1010101'; '011011']; B1 = '1010';
fprintf('\nConvert a binary representation B to its Sign-Magnitude Format Decimal integer D! \n');
fprintf('\n --%15s-- Sign-Magn representation is : %10d \n', B1, bin2sm(B1) ); B2 = '011011011';
fprintf('\n --%15s-- Sign-Magn representation is : %10d \n', B2, bin2sm(B2) ); B3 = '11001';
fprintf('\n --%15s-- Sign-Magn representation is : %10d \n', B3, bin2sm(B3) ); B4 = '1010101';
fprintf('\n --%15s-- Sign-Magn representation is : %10d \n', B4, bin2sm(B4) ); B5 = '011011';
fprintf('\n --%15s-- Sign-Magn representation is : %10d \n', B5, bin2sm(B5) );
用到的子函数sm2bin
function B = sm2bin(D);
% Convert a Sign-Magnitude format Decimal integer D
% to its binary representation B
% ----------------------------------------------------------
% B = sm2bin(D)
% D = sign-magnitude format decimal integer
% B = binary representation
%
% s = sign(D); % sign of D (-1 if x<0, 0 if x=0, 1 if x>0)
sb = (s < 0); % sign-bit (0 if x>=0, 1 if x<0)
B = strcat( num2str(sb), dec2bin( abs(D) ) );
另一个子函数bin2sm
function D = bin2sm(B);
% Convert a binary representation B to its
% Sign-Magnitude format Decimal integer D
% ----------------------------------------------------------
% D = bin2sm(B)
% D = sign-magnitude format decimal integer
% B = binary representation
%
%
%B = num2str(B)
sb = str2num( B(1) ); % sign-bit (0 if x>=0, 1 if x<0) if sb == 0
D = (1-sb) * bin2dec( B(2:length(B)) ); % or D = bin2dec( B(2:1:length(B)) )
elseif sb == 1
D = -bin2dec( B(2:length(B)) );
end
运行结果:
第6章的习题我就做到这里了,剩下的不会,以后开始第7章。