File Exchange

image thumbnail

Two's Complement for MATLAB

version 1.0 (617 Bytes) by

Calculating two's complement for a decimal number.



No License

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

Comments and Ratings (8)


Dw_N (view profile)

function [data_out] = twos_comp(data, bits)
% twos_comp converts input variable
% "data" to it's twos complement
% value. Input variable "data" is
% expected to be hexadecimal.

data_out = hex2dec(data) ;

if data_out >= 2^(bits - 1)
    data_out = data_out - 2^bits ;


Robert (view profile)

How about this...

twos = 1+bitcmp(uint16(-x));


duanra (view profile)

 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))

Hassan Naseri

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

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;
    value = y;

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.

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.

igi donegor

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.

MATLAB Release
MATLAB 6.5 (R13)

Inspired: Two's Complement

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video