Two's complement and negative numbers
Integers
Integers are numbers with no fractional part, that can be both positive, negative or zero. Usually uses a sign (-) to designate a negative integer.
The computer cannot store sign, because of only store information in bits, with zero or one value.
In C data types are 1, 2, 4, 8-, 16-, 32- or 64-bytes length, and the integers can be signed or unsigned.
Unsigned int store values from 0 to 2^n-1
Signed int store values from - (2^ (n - 1)) to 2^ (n – 1) as two’s complement binary format.
n is the number of bits in the machine.
Store Data
The computer can only store data in binary code because is the only language that computers understand. Languages like decimal are interpretations, and the machine has to translate it, from binary to hexadecimal, decimal, or octal. For instance, the number 15 is 1111 in binary, so the memory would be something like (usually 4 bytes):
Since int allocates 32 bits (4 bytes), fill the remaining 28 bits with 0.
0000 0000 0000 0000 0000 1111
MSB
The most significant bit is the sign, when zero, it means the number is positive, otherwise when is one means it is negative.
The compiler differentiates between positive and negative values from the MSB, if it's 1, means the number is negative. First takes the two's complement and then displays the number with a negative sign.
In a 32-bit system, the maximum value that can be stored is (2^31)-1, taking 31 bits in his representation.
Recommended by LinkedIn
Decoding
When the MSB is 0, the value is positive and only needs to make a base conversion from base 2 to base 10.
In most implementations, negative signed integers are stored in what is called two’s complement.
The two's complement of an N-bit number x is defined as 2^N - x.
One’s complements
In this representation, negative numbers are created from the corresponding positive number by flipping all the bits and not just the sign bit. The bad side is that there are two distinct representations for +0 and -0. The flipping of all the bits makes this harder to understand for humans.
Two’s complements
This is the most common representation for negative integers. This can also be calculated by flipping the bits of x and adding one.
For instance, the decimal number 48 in binary is:
0011 0000
The two’s complement is:
1101 0000
In the Github repository above you can see one C algorithm to make the conversion in both directions. The binary_to_code.c contains a prototype and an entry point to apply the two's complement.
Overflow
In unsigned arithmetic, a carry of the most significant digit means that there has been an overflow.
Questions?
If want to know more contact me. And join me on Github to collaborate coding.
Excelent ! ❤️