No BSD License  

Highlights from
Two's Complement for MATLAB

4.0

4.0 | 5 ratings Rate this file 52 Downloads (last 30 days) File Size: 617 Bytes File ID: #5485

Two's Complement for MATLAB

by Tal Levinger

 

13 Jul 2004 (Updated 19 Jul 2004)

Calculating two's complement for a decimal number.

| Watch this File

File Information
Description

Calculate two's complement for a signed integer in MATLAB.

Acknowledgements
This submission has inspired the following:
Two's Complement
MATLAB release MATLAB 6.5 (R13)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (6)
02 Jan 2007 Shyang-Wen Tseng

It is fascinating to read the author's wit of how to program to get the two's complement of an integer number. It is very useful not only in its usage but also its wit of programing it. Thank you.

22 Apr 2007 igi donegor  
07 May 2007 Chad Webb

Handy for 16 bit numbers, but not anything else. It even takes an input for what appears to be the number of bits (i.e. other than 16), but never utilizes it. Good start on a function that could be far more useful.

07 Sep 2007 Rafael Baur

there is a easier way to calculate the two's complement:
twos_comp = dec2bin(mod((value),2^bits),bits);

look at a those two's complement circles then you will see why it works.

13 Nov 2010 Hassan Naseri

function value = dec2tc(dec, N)
value = dec2bin(mod((dec),2^N),N);
end

function value = tc2dec(bin,N)
val = bin2dec(bin);
y = sign(2^(N-1)-val)*(2^(N-1)-abs(2^(N-1)-val));
if ((y == 0) && (val ~= 0))
  value = -val;
else
    value = y;
end
end

30 Jan 2012 duanra

 if N is the number of bit
and b an array of integer to convert in signed this operation could be faster

       if( b(n) > (2^(N-1)-1))
            b(n)=b(n)-2^N;
        else
            b(n)=b(n);
        end;

Please login to add a comment or rating.
Tag Activity for this File
Tag Applied By Date/Time
twos complement Tal Levinger 22 Oct 2008 07:27:34
matlab Tal Levinger 22 Oct 2008 07:27:34
calculate Tal Levinger 22 Oct 2008 07:27:34
signed integer Tal Levinger 22 Oct 2008 07:27:34
twos complement Remya Ajai 01 Feb 2010 05:26:04
twos complement Sven 20 Jul 2010 13:02:37

Contact us at files@mathworks.com