关于比特的对齐

时间:2012-10-03 05:51:30

标签: c binary bit-manipulation

说我有两个变量x和y,我想对齐最重要的1,我怎么用C写这个?例如,我有x = 11和y = 1011,我想将x与y对齐,使其成为1100.我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

运行BitScanReverse(或适用于您的编译器的内部函数,如GCC的__builtin_clz),从较大的值中减去较小的值,然后将较小的值向右移动。

答案 1 :(得分:0)

如paulsm4建议您可以确定数字的最高有效“SET”位并将其移位。 从中衍生出一个相当简化的版本可能是: -

int Num1_bit_count = 0,Num2_bit_count = 0;
int Num1 = 0b1100, Num2 = 0b0011, temp = 0;

    temp = Num1;  //Let's copy it in other variable to save the value of Num1
     //Count Number of bits in Num1
     while(temp > 0)
     {
         temp = temp >> 1;
         Num1_bit_count++;

     }
    //Same for Num2
    temp = Num2;  //Let's copy it in other variable to save the value of Num2
     //Count Number of bits in Num1
     while(temp > 0)
     {
         temp = temp >> 1;
         Num2_bit_count++;

     }

  if(Num1_bit_count > Num2_bit_count)
   {
       Num2 = Num2 << (Num1_bit_count - Num2_bit_count);

   }
  else if(Num2_bit_count > Num1_bit_count)
   {
       Num1 = Num1 << (Num2_bit_count - Num1_bit_count);

   }