Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
hi everyone
I want to compare 2 number with them for example 2 and 3
and my program do this operations with bitwise operators.
i dont know how write this program
help pls
tanx
Posted
Comments
Richard MacCutchan 28-Sep-12 4:17am    
What do you mean by "with bitwise operators", what result are you trying to obtain?
meysamp73 28-Sep-12 4:29am    
& The AND operator
| The OR operator
^ The XOR operator
~ The Ones Complement or Inversion operator
>> The Right Shift operator
<< The Left Shift operator.

for example we receive 2 , 3 numbers from input and show 3 is greater than 2
Richard MacCutchan 28-Sep-12 4:56am    
Why not just use the math operators like > == etc.?

For unsigned numbers you may simply right shift the numbers, until their leading bit (MSB) is different. e.g.
(I'm pretty sure there are more efficient ways, have a look, if you can at "Hacker's Delight"[^] book).

C
#include <stdlib.h>
#include <stdio.h>

int compare(unsigned int a, unsigned int b);
int main()
{
  unsigned int a, b;
  int i;

  for (i = 1; i<20; i++)
  {
    a =rand();
    b= rand();
    switch (compare(a,b))
    {
    case -1:
      printf("%u is smaller than %u\n", a, b);
      break;
    case 0:
      printf("%u is equal to %u\n", a, b);
      break;
      case 1:
      printf("%u is greater than %u\n", a, b);
      break;
    }
  }
  return 0;
}

int compare(unsigned int a, unsigned int b)
{
  unsigned int fb = 1 << (sizeof(a)*8-1);

  while ( !( (a ^ b) & fb))
  {
    a <<= 1;
    b <<= 1;
    if (!a && !b) return 0;
  }
  if ( a & fb)
    return 1;
  else
    return -1;
}
 
Share this answer
 
v3
Comments
nv3 28-Sep-12 5:34am    
Nice job. You just forgot to replace the < escape sequences which makes the source somewhat difficult to read.
CPallini 28-Sep-12 5:41am    
Ooops!
Thanks and sorry for the inconvenience, it should be OK now.
Malli_S 28-Sep-12 6:51am    
+5.
CPallini 29-Sep-12 9:31am    
Thanks.
Espen Harlinn 29-Sep-12 6:57am    
5'ed!
What about:
C++
int integer1 = 666;
int integer2 = 666;
int result = integer1 & integer2; //bitwise AND
if(result == integer1)
{
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900