2s complement in C | Two's Complement Basics

 

What is the 2s complement in C

The 2s complement in C is generated from the 1s complement in C. As we know that the 1s complement of a binary number is created by transforming bit 1 to 0 and 0 to 1; the 2s complement of a binary number is generated by adding one to the 1s complement of a binary number.

2s complement in C


In short, we can say that the 2s complement in C is defined as the sum of the one's complement in C and one.

2s complement in C

In the above figure, the binary number is equal to 00010100, and its one's complement is calculated by transforming the bit 1 to 0 and 0 to 1 vice versa. Therefore, one's complement becomes 11101011. After calculating one's complement, we calculate the two's complement by adding 1 to the one's complement, and its result is 11101100.

Two's Complement Basics:

  1. Positive Numbers: In two's complement, positive numbers are represented just like in regular binary representation. There is no special treatment for them. For example, the decimal number 5 is represented as 00000101 in 8-bit two's complement binary.

  2. Negative Numbers: Negative numbers are represented by taking the two's complement of their absolute value.

    To obtain the two's complement of a binary number, follow these steps:

    1. Invert (flip) all the bits (change 0s to 1s and vice versa).
    2. Add 1 to the inverted result.

Example: Representing -5 in Two's Complement Binary (8-bit):

  1. Represent +5 in binary: The binary representation of +5 is 00000101.

  2. Invert all the bits: Flip all the bits to get 11111010.

  3. Add 1 to the result: Add 1 to 11111010 to get 11111011.


So, -5 is represented as 11111011 in 8-bit two's complement binary.

Now, let's write a C program to demonstrate two's complement representation:
c
#include <stdio.h> int main() { int positiveNumber = 5; // Positive number int negativeNumber = -5; // Negative number // Display positive and negative numbers in binary printf("Positive number (5) in binary: "); for (int i = 7; i >= 0; i--) { printf("%d", (positiveNumber >> i) & 1); } printf("\n"); printf("Negative number (-5) in binary: "); for (int i = 7; i >= 0; i--) { printf("%d", (negativeNumber >> i) & 1); } printf("\n"); return 0; }
When you run this code, it will display the binary representations of both the positive and negative numbers. You'll see that -5 is represented as 11111011 in two's complement binary, which matches our previous example.In summary, two's complement in C is a binary representation scheme for signed integers that simplifies arithmetic operations and efficiently represents both positive and negative numbers. It is essential to understand two's complement when working with integers in computer programming.

Post a Comment

0 Comments