NOTE ON THE TWO'S COMPLEMENT NUMBER CODE

Two's complement is the most common number code for storing integer values. Considering the following 8 bit "value box":

-128 64 32 16 8 4 2 1

Using this box and given the binary number 10001101, this will be equivalent to -128+8+4+1 = -115. Thus any two's complement number with a leading 1 represents a negative number (and vice-versa). Therefore, in the above case, the largest negative number that can be stored is -128, and the largest positive number is 127.

To give two further examples the number 1 would be represented by the bit pattern 00000001, and the number -1 by the bit pattern 11111111.


A short C programme to output a two's complement number in binary format

#include <stdlib.h>

void main(int argc, char *argv[])
{
int i = 1, addr;
unsigned long int n;

/* Check Input */

if (argc != 2) {
        printf("INPUT ERROR.\n");
        exit(1);
        }
else addr = atoi(argv[1]);

/* Output */

for(n=2147483648;n>0;n=n/2) {
        if (i==9) {
                printf(" ");
                i=2;
                }
        else i++;
        if (addr & n) printf("1");
        else printf("0");
        }

printf("\n");
}

Input integer i and .




Created and maintained by Frans Coenen. Last updated 03 July 2001