代码:
%% ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ %% Output Info about this m-file fprintf(' *********************************************************** '); fprintf(' <DSP using MATLAB> Problem 6.24 '); banner(); %% ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ D = [1001, -63, -449, 978, -205]; fprintf(' Convert a Sign-Magnitude Format Decimal integer D to its binary representation B! '); fprintf(' %5d binary representation is :-- %20s -- ', D(1), sm2bin(D(1)) ); fprintf(' %5d binary representation is :-- %20s -- ', D(2), sm2bin(D(2)) ); fprintf(' %5d binary representation is :-- %20s -- ', D(3), sm2bin(D(3)) ); fprintf(' %5d binary representation is :-- %20s -- ', D(4), sm2bin(D(4)) ); fprintf(' %5d binary representation is :-- %20s -- ', 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(' Convert a binary representation B to its Sign-Magnitude Format Decimal integer D! '); fprintf(' --%15s-- Sign-Magn representation is : %10d ', B1, bin2sm(B1) ); B2 = '011011011'; fprintf(' --%15s-- Sign-Magn representation is : %10d ', B2, bin2sm(B2) ); B3 = '11001'; fprintf(' --%15s-- Sign-Magn representation is : %10d ', B3, bin2sm(B3) ); B4 = '1010101'; fprintf(' --%15s-- Sign-Magn representation is : %10d ', B4, bin2sm(B4) ); B5 = '011011'; fprintf(' --%15s-- Sign-Magn representation is : %10d ', 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章。