This is a very simple utility that computes the two's complement value from an unsigned integer input. The number of bits of the input integer must also be specified
Chad Webb (2021). Two's Complement (https://www.mathworks.com/matlabcentral/fileexchange/14900-two-s-complement), MATLAB Central File Exchange. Retrieved .
Similar to Jeremy, I don't see the functionality of the code if the input must be unsigned integer. Isn't the two's component mainly used to deal with negative numbers?
Hello, I hope you don't mind, I modified it a bit to handle matrices, and overflows. Cheers !
function value = TwosComplement(x, numBits)
if ~isnumeric(x) || ~isnumeric(numBits) || nargin ~= 2
error (' Function requires two numeric input arguments');
if numBits < 2
error ('numBits should be at least 2 for a Twos Complement representation');
% Create MSB matrix (Shift right, and truncate remaining bits if any)
msb = mod(bitshift(x, -(numBits - 1) ),2);
% Calculate all positive values (Truncate the input)
value = mod(x,2^(numBits - 1));
% Calculate all negative values (Invert and add 1)
neg = -1 * ( bitcmp(mod(x, 2^(numBits -1)), numBits -1) + 1 );
% Use MSB matrix as a mask to choose either the positive or negative value
value(msb ~= 0)= neg(msb ~= 0);
um...the 2's complement of an unsigned value is just the dec2bin function...what's the point if it's unsigned?
Would be nice if this were vectorized. That would mean not using the if statement but instead operating on the entries where msb was true, but not the others.
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!