Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 转换为基数2,然后拆分为一个数组_C#_Arrays_Base - Fatal编程技术网

C# 转换为基数2,然后拆分为一个数组

C# 转换为基数2,然后拆分为一个数组,c#,arrays,base,C#,Arrays,Base,我想将基数10转换为基数2,然后将零件存储在数组中 以下是两个例子: 我的值是5,所以它将被转换为101,然后我有一个如下的数组:{1,0,1} 或者我的值是26,所以它将被转换为11010,然后我将有一个如下的数组:{0,1,0,1,1} 提前感谢您的时间和考虑。要转换int'x' int x = 3; 一种方法是,通过对int进行操作: string s = Convert.ToString(x, 2); //Convert to binary in a string int[] bit

我想将基数10转换为基数2,然后将零件存储在数组中

以下是两个例子:

我的值是5,所以它将被转换为101,然后我有一个如下的数组:{1,0,1}

或者我的值是26,所以它将被转换为11010,然后我将有一个如下的数组:{0,1,0,1,1}

提前感谢您的时间和考虑。

要转换int'x'

int x = 3;
一种方法是,通过对int进行操作:

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

int[] bits= s.PadLeft(8, '0') // Add 0's from left
             .Select(c => int.Parse(c.ToString())) // convert each char to int
             .ToArray(); // Convert IEnumerable from select to Array
或者,通过使用BitArray类-

BitArray b = new BitArray(new byte[] { x });
int[] bits = b.Cast<bool>().Select(bit => bit ? 1 : 0).ToArray();
BitArray b=新的位数组(新字节[]{x});
int[]bits=b.Cast().Select(bit=>bit?1:0).ToArray();

来源:

欢迎来到StackOverflow!到目前为止你试过什么?当您陷入代码困境时,我们很乐意为您提供帮助,但这不是免费的编码服务。请搜索DEC to BINARY STRING函数。反转输出。将其添加到数组中。将此问题标记为重复问题,而不是复制其他人的答案1:1@fubo是的,你说得对