2

我有以下内容:

public int [] PermuteNum(int num)
{
int[] newArray = new int[16];
string strNum = Convert.ToString(num, 2);
int[] bits = strNum.PadLeft(16, '0').Select(c => int.Parse(c.ToString())).ToArray();

for (int i = 0; i < bits.Length; i++)
{

int newBit = P(i);
int NewNum = bits[newBit];
newArray[i] = NewNum;

}

return newArray;
}

如何将这个 1 和 0 数组转换回我的初始int?第一个元素是最高有效位。

4

3 回答 3

2
int result = 0;
for (int i = 0; i < newArray.Length; i++)
{
    result *= 2;
    result += newArray[i];
}
于 2012-11-17T02:49:57.237 回答
1

您可以使用按位移位操作。这是伪代码,您可以对位移操作进行研究:

int accumulator = 0;
  int i = 0;
//this assumes your lowest bit is the first one, reverse order if not
foreach(var bit in bits)
{  
  //when you get to the 3rd bit(i==2), if bit is 1 then it represents 2^2 == 8, 
  //to calculate the value of the bit, isntead of using 2^i power, just shift i places

  //Example: the array 1,0,1 becomes 
  // accumulator +=  2^0 // accumulator now == 1
  // accumulator +=  0^1 // accumulator now == 1
  // accumulator +=  2^2 // accumulator now == 4

  accumulator += (shiftbit by i positions);
  ++i;
}
于 2012-11-17T02:08:33.420 回答
0

也许您可以使用BitArray并使用另一个问题的答案将其排列转换回int

于 2012-11-17T02:15:49.543 回答