将2的数字与按位运算进行比较 [英] compare 2 number with bitwise operations

查看:108
本文介绍了将2的数字与按位运算进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好
我想将2的数字与它们进行比较,例如2和3
和我的程序使用按位运算符执行此操作.
我不知道该怎么写程序
帮助请
tanx

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

推荐答案

对于无符号数字,您可以简单地将数字右移,直到其前导位(MSB)不同.例如
(如果您可以通过黑客的喜悦" [ ^ ]书).

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;
}


有关:
int integer1 = 666;
int integer2 = 666;
int result = integer1 & integer2; //bitwise AND
if(result == integer1)
{
}


bool equals_bitwise(int x,int y)
{
返回x ^ y == 0;
}
bool differents_bitwise(int x,int y)
{
返回x ^ y!= 0;
}
bool equals_bitwise(int x, int y)
{
return x ^ y == 0;
}
bool differs_bitwise(int x, int y)
{
return x ^ y != 0;
}


这篇关于将2的数字与按位运算进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆