【问题标题】:Convert array/list to a binary number, based on value of list element: 0 or not 0 [closed]根据列表元素的值将数组/列表转换为二进制数:0 或非 0 [关闭]
【发布时间】:2017-01-23 16:58:54
【问题描述】:

我收到一个包含 4 个数字的数组/列表。首先,我想将其转换为二进制数组,然后将其转换为十进制。 (我了解到,这可以通过“聚合”功能实现。) 二进制值用于根据数组中的位置将真/假值分配给 4 个变量。 如果列表元素的值 = 0 则二进制值 = 0 = false,如果值 0 则二进制值 =1 = true。

所有 4 个数字始终为正数。例如。

{40 60 80 100} --> {1 1 1 1} --> 15(十进制) --> 位置 1 = 真;位置2 =真;位置3 =真;位置 4 = 真;

{20 0 40 80} --> {1 0 1 1} --> 11(十进制) --> 位置 1 = 真;位置 2 = 假;位置3 =真;位置 4 = 真;

{0 0 20 50} --> {0 0 1 1} --> 3(十进制) --> 位置 1 = 假;位置 2 = 假;位置3 =真;位置 4 = 真;

谢谢!

我使用的解决方案:

double [] source = new double[] {10,20,0,10};
int result = source.Aggregate(0, (a, x) => (a << 1) | (x == 0 ? 0 : 1));

var bools = new BitArray(new int[] { result }).Cast<bool>().ToArray();

position 1 = bools[0]; //true
position 2 = bools[1]; //true
position 3 = bools[2]; //false
position 4 = bools[3]; //true

//16/09 编辑:添加到请求中并使其更具体
//第二次编辑:添加了我使用的解决方案。

【问题讨论】:

  • 使其更具体。并找到并添加了解决方案。

标签: c# arrays binary boolean converter


【解决方案1】:

这是一个非常简单易懂的方法:

var inputCollection = new List<int> { 40, 60, 80, 100 };
var binaryStringBuilder = new StringBuilder();
foreach (var input in inputCollection)
{
    binaryStringBuilder.Append(input == default(int) ? 0 : 1);
}

var binaryRepresentation = binaryStringBuilder.ToString();
var decimalRepresentation = Convert.ToInt32(binaryRepresentation, 2).ToString();
Console.WriteLine("Binary representation: {0}", binaryRepresentation);
Console.WriteLine("Decimal representation: {0}", decimalRepresentation);

【讨论】:

    【解决方案2】:

    另一种选择是先构建实际位表示,然后将其转换为十进制:

    var bitsString = string.Join(string.Empty, list.Select(x => x == 0 ? 0 : 1));
    var result = Convert.ToInt32(bitsString, 2)
    

    【讨论】:

      【解决方案3】:

      只需 Aggregate int[]List&lt;int&gt; 通过 Linq

        int[] source = new int[] { 20, 0, 40, 80 };
      
        int result = source.Aggregate(0, (a, x) => (a << 1) | (x == 0 ? 0 : 1));
      

      测试:

        // "1011 or 11 (decimal)"
        Console.Write(String.Format("{0} or {1} (decimal)",
          Convert.ToString(result, 2), result));
      

      【讨论】:

        猜你喜欢
        • 2016-12-20
        • 2013-01-09
        • 1970-01-01
        • 2021-03-10
        • 2018-02-23
        • 2019-09-07
        • 2021-01-31
        • 2014-07-29
        • 1970-01-01
        相关资源
        最近更新 更多