1

假设我有两个变量 x 和 y,并且我想对齐最重要的 1,我将如何用 C 编写这个?例如,我有 x=11 和 y = 1011,我想将 x 与 y 对齐,使其为 1100。我该怎么做?

4

2 回答 2

2

运行BitScanReverse(或适合您的编译器的内在函数,例如__builtin_clzGCC),从较大的值中减去较小的值,然后将较小的值向左移动。

于 2012-10-03T06:22:29.033 回答
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);

   }
于 2012-10-03T06:29:51.607 回答