File Exchange

image thumbnail

Two's Complement

version 1.0.0.0 (767 Bytes) by Chad Webb
Compute the two's complement value of an unsigned integer

4 Downloads

Updated 07 May 2007

No License

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

Cite As

Chad Webb (2021). Two's Complement (https://www.mathworks.com/matlabcentral/fileexchange/14900-two-s-complement), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (4)

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?

Anthony Ghannoum

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');
end
if numBits < 2
error ('numBits should be at least 2 for a Twos Complement representation');
end
% 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);
end

Jeremy

um...the 2's complement of an unsigned value is just the dec2bin function...what's the point if it's unsigned?

Loren Shure

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.

MATLAB Release Compatibility
Created with R14
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!