【问题标题】:Convert to base 2 then split in an array [duplicate]转换为基数 2,然后拆分为数组 [重复]
【发布时间】:2016-06-03 12:48:42
【问题描述】:

我想将我的以 10 为底的数字转换为以 2 为底的数字,然后将部分存储在一个数组中。

这里有两个例子:

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

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

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

【问题讨论】:

  • 欢迎来到 StackOverflow!你都尝试了些什么?当您陷入代码困境时,我们愿意为您提供帮助,但 SO 不是免费的编码服务。
  • 搜索 DEC 到 BINARY STRING 函数。反转输出。将其添加到数组中。

标签: c# arrays base


【解决方案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();

来源:https://stackoverflow.com/a/6758288/1560697

【讨论】:

  • 如何将此问题标记为重复而不是复制其他人的答案 1:1
  • @fubo 是的,你是对的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-26
  • 2016-01-06
  • 1970-01-01
  • 2017-04-14
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
相关资源
最近更新 更多