Be the first to rate this file! 25 Downloads (last 30 days) File Size: 1.55 KB File ID: #14900

Two's Complement

by Chad Webb

 

07 May 2007 (Updated 07 May 2007)

Compute the two's complement value of an unsigned integer

| Watch this File

File Information
Description

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

Acknowledgements

The author wishes to acknowledge the following in the creation of this submission:
Two's Complement for MATLAB, from decimal to two's complement

MATLAB release MATLAB 7 (R14)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (4)
09 May 2007 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.

30 Oct 2008 Jeremy

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

10 Dec 2010 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

03 Aug 2011 Przemyslaw Zelazowski

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?

Please login to add a comment or rating.
Tag Activity for this File
Tag Applied By Date/Time
twos complement Chad Webb 22 Oct 2008 09:12:01
compute Chad Webb 22 Oct 2008 09:12:01
utility Chad Webb 22 Oct 2008 09:12:01
unsigned Chad Webb 22 Oct 2008 09:12:01
integer Chad Webb 22 Oct 2008 09:12:01
twos complement Javier 17 Oct 2011 05:23:28

Contact us at files@mathworks.com