上代码:
% x = -8:7 y = TwosComplement(x, 4) y = dec2bin(y, 4); disp(sprintf('%s', [y'; char(ones(1, 16) * 32)]))
函数TwosComplement代码:
function [y] = TwosComplement(x, B); % Decimal equivalent of Sign-Magnitude format integer % to B-bit Twos'-Complement format conversion % ---------------------------------------------------------- % [y] = ladrfilt(x, B) % x = integer between -2^(B-1) < x < 2^(B-1) (sign-magnitude) % y = integer between 0 <= y <= 2^b-1 (2's-complement) % % if any((x < -2^(B-1) | (x >= 2^(B-1)))) error('Numbers must satisfy -2^(B-1) <= x < 2^(B-1)') end s = sign(x); % sign of x (-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) y = (1-sb) .* x + sb .* (bitcmp(abs(x), B) + 1); % y = (1-sb) .* x + sb .* (2^B + x)
运行结果: