Continue to Site

# How to calculate 2's compelement in MATLAB?

Status
Not open for further replies.

#### testing test

##### Member level 3
Hi,

I want to find the 2's complement of -127 in MATLAB for 8 bits. I want to find 2's complement of a. So, I multiply it by -1 and takes its dec2bin:

Code:
a=-127
a=-1*a;
b=dec2bin(a,8);

Now b = '01111111'

I want to invert all the bits of b and add 1 to it. How can I do it?

Thank you.

I can sugest you perform in DEC radix, adding following step previous above code :

Code:
a = 256 - a + 1 ;

+++

Isn't 256-a only?

testing test

### testing test

Points: 2
Well, what I actually want is to convert
-127 to 129
-126 to 130
-125 to 131

And so on...

@andre_teprom: Your provided equation is not doing this.

@KerimF: Yes man it worked. Thanks!

you can use a for loop

....andre_teprom: Your provided equation is not doing this...

Please post what result was returned.

+++

These two lines worked fine:

a=-127;
a=256+a;

Thank you.

Status
Not open for further replies.