Write a C program to check if two integers have opposite or same signs using bitwise operators

Two integers have opposite signs if their most significant bits (msb) are different. The most significant bit (also the sign bit for a signed integer) of any negative number will always be 1, on the contrary it will always be 0 if the number is positive. Following that, if bitwise operator exclusive OR (XOR "^") is applied on two integers of opposite signs, the resultant number will be a negative one. Because most significant bits of both numbers will not be the same and in that case XOR operation will produce 1 (as XOR operator results zero only when it is applied on 2 zeroes or 2 ones) that makes the resultant a negative number.

Hence, the result of bitwise exclusive OR applied on two integers will be less than zero, if numbers are of opposite signs.

Note that this solution of checking opposite signs of two numbers is for integers, because bitwise operators operate on char and int only.

C program to check whether two integer variables have same or different sings.

/* Write a C program to check if two integers have opposite signs. */
 
#include <stdio.h>
int main()
{
  int n1, n2; //declare two integers
  printf ("Enter two integer values: ");
  scanf ("%d%d", &n1, &n2);
 
  if ((n1 ^ n2) < 0)
  {
    printf ("Both numbers (%d, and %d) have opposite signs.\n", n1, n2);
  }
  else
  {
    printf ("Both numbers (%d, and %d) have same sign.\n", n1, n2);
  }
 
  return 0;
}

Hope you have enjoyed reading C program for checking if two integers have opposite or same signs using bitwise operators. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!



Get Free Tutorials by Email

About the Author

is the main author for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.

Today's Tech News

Plans drawn up for world's tallest wooden skyscraperPosted on Monday February 19, 2018

The 70-storey tower would be 90% wood and have trees and other foliage on every level.

Probe after 'drone made helicopter crash'Posted on Monday February 19, 2018

Investigations are launched after a helicopter reportedly crashed after swerving to avoid a consumer drone.

Dark web paedophile Matthew Falder jailed for 32 yearsPosted on Monday February 19, 2018

Matthew Falder blackmailed victims into sending sexual images that he then shared on the dark web.

Courtesy BBC News

AD BLOCKER DETECTED!

Advertisements help running this site for free.


To view the content please disable AdBlocker and refresh the page.

×