English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

2006-10-07 09:59:22 · 2 answers · asked by valerie cortez 1 in Science & Mathematics Mathematics

assuming that the integer size is 8 bits

2006-10-07 10:05:31 · update #1

2 answers

You can simply add or subtract them as binary values without regard for the fact that they are in 2's complement form.

The result will also be in 2's complement form.

ex. 0xF0 - 0x02 (in decimal)

11110000 (-16 in decimal)
- 00000010 (+2 in decimal)
----------------
11101110 (0xEE in 2's complement)

Ans = 0xEE in 2's complement, or a value of -18 in decimal

Here's how to convert from binary to 2's complement form if you don't already know.

Ignore the sign for a moment. Represent the magnitude of the value as a positive binary value.

Then, invert all of the bits and add 1 to the result to get to 2's complement form.

Do the same thing to get back to straight binary. Invert the bits and add 1. You just need to remember that if the MSB of the value in 2's complement form represents a negative number.

Example

Represent -2 in 2's complement form

0010 (value of 2)
1101 (bits inverted)
1110 (add 1. This is the the 2's complement, and is equal to -2)

Now to convert back.
1110 (2's complement)
0001 (invert the bits)
0010 (add 1. This is the magnitude, equal to 2.)

In 2's complement form, you can add and subtract values without regard to sign. That's the big advantage of it. The result can then be converted back to straight binary.

2006-10-07 10:33:31 · answer #1 · answered by Guru 6 · 1 0

Adding: go ahead and add them normally. If you get a 9-digit number, it means overflow, because you've added two negative numbers that are large enough to go past the smallest negative number that can be represented.

Example: 0xF0 = -16, 0x02 = +2, sum = 0xF2 = -14 in 2's complement.

Subtracting: re-do the 2's complement on the number you're subtracting. For example, 0x02 = +2 changes to 0xFE = -2. Then add, and discard any bits past the nth bit, where n is the number of bits used to represent numbers. In this case, -16-2 = 0xF0 + 0xFE = 0xEE = -18 in 2's complement.

2006-10-07 17:34:57 · answer #2 · answered by James L 5 · 0 1

fedest.com, questions and answers