Highlights from Two's Complement for MATLAB

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

Two's Complement for MATLAB

Tal Levinger (view profile)

13 Jul 2004 (Updated )

Calculating two's complement for a decimal number.

File Information
Description

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

Acknowledgements

This file inspired Two's Complement.

MATLAB release MATLAB 6.5 (R13)
04 Apr 2016 Dw_N

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

data_out = hex2dec(data) ;

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

Comment only
23 Feb 2012 Robert

Robert (view profile)

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

Comment only
30 Jan 2012 duanra

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))
b(n)=b(n)-2^N;
else
b(n)=b(n);
end;

Comment only
13 Nov 2010 Hassan Naseri

Hassan Naseri (view profile)

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

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.