将数组0和1转换为c#中的int

时间:2012-11-17 02:04:16

标签: c#

我有以下内容:

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 ?第一个元素是最重要的部分。

3 个答案:

答案 0 :(得分:2)

int result = 0;
for (int i = 0; i < newArray.Length; i++)
{
    result *= 2;
    result += newArray[i];
}

答案 1 :(得分:1)

您可以使用按位移位操作。这是peudo代码,你可以对比特转换操作进行研究:

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

答案 2 :(得分:0)

也许您可以使用BitArray并使用another question的答案将其排列转换回 int