Two's Complement

From bildr

Jump to: navigation, search

Definition

Two's complement is a way of storing signed integers in binary format. It uses the mechanism of integer overflow to make the sum of all negated values equal a single zero value. (compare to One's complement which has both positive and negative zero).

The primary way to convert a two's complement number to its negative counterpart is to logically invert it and then add 1.

'Example:'

In 16 bit systems the number five is represented as

0x0005 = 0000000000000101

Logical negation (replace ones with zeros and vice versa)

~0x0005 = 1111111111111010

And the addition of one results in negative 5

-5 = 1111111111111011

To check our work we can add them together

carry | 1111111111111111
 5    |  0000000000000101
-5    |+ 1111111111111011
      |--------------------
0     |  0000000000000000


How to use it

As stated above, to find the two's complement negation of a number, use the bitwise negation and then add one.

-x = ~x+1

This can be used in systems that may not have explicit support for signed integers.

This page is an Article on bildr. Articles are pages that define or explain a concept, method, or generic item.

NOTE: All information contained within this article is pure opinion. Although this article is intended to help people, it may contain faulty or misleading information. This article is not to be considered professional opinion or advice, and is in no way a replacement for reading all safety/instructional documentation. Always remember to protect yourself when handling/using hazardous materials, as well as test new techniques before using them on projects/work intended to be handed in or used.

bildr and its contributers take NO responsibility for the information contained within.