# c# 陣列轉int - 將int轉換為.NET中的位數組

## int轉char c#陣列轉數字 (7)

``````int x = 3;
``````

``````string s = Convert.ToString(x, 2); //Convert to binary in a string

.Select(c => int.Parse(c.ToString())) // convert each char to int
.ToArray(); // Convert IEnumerable from select to Array
``````

``````BitArray b = new BitArray(new byte[] { x });
int[] bits = b.Cast<bool>().Select(bit => bit ? 1 : 0).ToArray();
``````

``````0 0 0 0 0 0 1 1
``````

``````using System;
using System.Collections;

namespace Questions
{
class Program
{
static void Main(string[] args)
{
//get bit Array for number 20
var myBitArray = new BitArray(BitConverter.GetBytes(20));
}
}
}
``````

``````if (myBitArray[0] == false)
{
//this code block will execute
}
``````

``````if (myBitArray[0] == 0)
{
//some code
}
``````

``````int val = 2097152;
var arr = Convert.ToString(val, 2).ToArray();
var myVal = arr[21];
``````

......沒有產生我想要的結果。 在上面的'myVal'中，存儲在位置21的數組中的值為'0'。 應該是'1'。 我不確定為什麼我收到了一個不准確的值，它讓我感到困惑，直到我在C＃中找到另一種方法將INT轉換為位數組：

``````int val = 2097152;
var arr = new BitArray(BitConverter.GetBytes(val));
var myVal = arr[21];
``````

``````int value = 3;
BitArray b = new BitArray(new int[] { value });
``````

``````bool[] bits = new bool[b.Count];
b.CopyTo(bits, 0);
``````

``````byte[] bitValues = bits.Select(bit => (byte)(bit ? 1 : 0)).ToArray();
``````

``````int value = 3;

var array = Convert.ToString(value, 2).PadLeft(8, '0').ToArray();
``````

``````    public static bool[] Convert(int[] input, int length)
{
var ret = new bool[length];
var siz = sizeof(int) * 8;
var pow = 0;
var cur = 0;

for (var a = 0; a < input.Length && cur < length; ++a)
{
var inp = input[a];

pow = 1;

if (inp > 0)
{
for (var i = 0; i < siz && cur < length; ++i)
{
ret[cur++] = (inp & pow) == pow;

pow *= 2;
}
}
else
{
for (var i = 0; i < siz && cur < length; ++i)
{
ret[cur++] = (inp & pow) != pow;

pow *= 2;
}
}
}

return ret;
}
``````

``````public enum QuestionType
{
Role = 2,
ProjectFunding = 3,
TotalEmployee = 4,
NumberOfServers = 5,
}
``````

...是一個很好的聲明。

``````int Question = (int)QuestionType.Role
``````

``````public class QuestionType
{
public static int Role = 2,
public static int ProjectFunding = 3,
public static int TotalEmployee = 4,
public static int NumberOfServers = 5,
public static int TopBusinessConcern = 6
}
``````

``````int Question = QuestionType.Role
``````