12,997,441 members (72,846 online)
Rate this:
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 27-Sep-12 22:15pm
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.?

Rate this:

## Solution 3

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).

```#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;
}```
v3
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!
CPallini 29-Sep-12 9:31am

Thank you.
Rate this:

## Solution 1

```int integer1 = 666;
int integer2 = 666;
int result = integer1 & integer2; //bitwise AND
if(result == integer1)
{
}```
v2
Rate this:

## Solution 4

bool equals_bitwise(int x, int y)
{
return x ^ y == 0;
}
bool differs_bitwise(int x, int y)
{
return x ^ y != 0;
}
CPallini 28-Sep-12 6:24am

That's correct, but not answers the OP question.
armagedescu 28-Sep-12 6:48am

Why not?
Richard MacCutchan 28-Sep-12 9:41am

OP wants to find out which number is greater.
armagedescu 28-Sep-12 10:35am

In mater of guessing you are right, but technically speaking I answered correctly to the question.

Top Experts
Last 24hrsThis month
 ppolymorphe 335 OriginalGriff 270 RickZeeland 265 F-ES Sitecore 130 Karthik Bangalore 110
 OriginalGriff 4,442 ppolymorphe 2,242 Kornfeld Eliyahu Peter 1,973 RickZeeland 1,901 Richard Deeming 1,543