Home  >  Article  >  Backend Development  >  Binary Number System - Arithmetic addition overflow in C/C++?

Binary Number System - Arithmetic addition overflow in C/C++?

PHPz
PHPzforward
2023-08-26 22:33:011023browse

2’s complement number system is widely used in computer architecture.

N-bit 2's complement number system can represent numbers from -2n-1 to 2n-1-1

4-bit can represent numbers from (-8 to 7)

5 bits can represent numbers from (-16 to 15) in the 2's complement system.

Overflow occurs in addition when 2 N-bit 2’s complement numbers are appended and the answer is too large to fit in that N-bit group.

The computer contains N-bit fixed registers. The result of adding two N-digit numbers will be the largest N 1-digit number.

The carry flag stores extra bits. But a carry doesn't always indicate an overflow.

Overflow detection

When-

  • the result of adding two negative numbers is a positive number or

  • The result of adding two negative numbers is a negative number.

Therefore, overflow can be detected by verifying the most significant bit (MSB) of both operands and the result. However, instead of implementing a 3-bit comparator, overflow can be detected by verifying the carry and carry output from the MSB. We consider N-bit addition of 2’s complement numbers.

二进制数系统 - C/C++中的算术加法溢出?

Overflow occurs when the carry input is not equal to the carry output. The above overflow expression can be discussed from the following analysis.

二进制数系统 - C/C++中的算术加法溢出?

In the first picture, the most significant bits of the two numbers are 0, indicating that they are positive numbers. Here, if the carry input is 1, we get the most significant bit of the result to be 1, indicating that the result is negative (overflow), and the carry output is 0. Carry in is not equal to carry out, so overflow occurs.

In the second picture, the most significant bits of the two numbers are 1, indicating that they are negative numbers. Here, if the carry input is 0, we get the most significant bit of the result to be 0, indicating that the result is positive (overflow), and the carry output is 1. Carry in is not equal to carry out, so overflow occurs.

Therefore, the MSB carry-in and carry-out are sufficient to detect overflow.

二进制数系统 - C/C++中的算术加法溢出?

The above XOR gate can be used to detect overflow.

The above is the detailed content of Binary Number System - Arithmetic addition overflow in C/C++?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete