check opposite signs Algorithm

The check opposite signs algorithm is a simple and efficient technique used to determine if two given numbers have opposite signs or not. This algorithm is particularly useful in various computer programming and mathematical applications, such as optimizing code, solving equations, and analyzing data. The basic idea behind this algorithm is to utilize the properties of the binary representation of numbers, specifically the most significant bit (MSB), which represents the sign of a number in two's complement notation. In this notation, positive numbers have their MSB set to 0, while negative numbers have their MSB set to 1. To implement the check opposite signs algorithm, one can use the bitwise XOR operation followed by the bitwise AND operation. First, the XOR operation is applied to the two input numbers, which will result in a new number with its MSB set to 1 if the input numbers have opposite signs and 0 otherwise. Then, the bitwise AND operation is performed between this new number and the highest possible number that can be represented with the same number of bits as the input numbers (e.g., for a 32-bit integer, the highest possible number is 2^31). If the result of the AND operation is non-zero, it signifies that the two input numbers have opposite signs, otherwise, they have the same sign. This method is fast and efficient, as it does not involve any arithmetic operations, such as multiplication or division, and relies solely on bitwise operations, which are typically faster on modern processors.
/*
 * Given two integers, using bit manipulations determine if they are of opposite signs.
 * Most Significant Bit (MSB) of number represents sign of the number. If it is 1, it represents
 * a negative value, if it is 0, it represents a positive value.
 * If MSB of two numbers are different, their XOR would be 1, otherwise it would be 0.
 * Thus, result of XOR of two numbers will have MSB 1 if they are of opposite signs,
 * 0 other wise, in other words, XOR of two numbers would be negative (MSB 1) if they are of
 * opposite signs.
 * Source : http://graphics.stanford.edu/~seander/bithacks.html
 */

#include <iostream>

 bool are_of_different_signs(int a, int b)
 {
     return ((a ^ b) < 0);
 }

 int main()
 {
     int a, b;
     std::cout << "Enter number 1: ";
     std::cin >> a;
     std::cout << "Enter number 2:";
     std::cin >> b;
     if (are_of_different_signs(a, b))
     {
         std::cout << a << " and " << b << " are of different signs" << std::endl;
     }
     else
     {
         std::cout << a << " and " << b << " are of same signs" << std::endl;
     }
     return 0;
 }

LANGUAGE:

DARK MODE: