【问题标题】:Divide single Value for a many in table C#将单个值除以表 C# 中的多个值
【发布时间】:2016-12-18 20:27:24
【问题描述】:

来自

int BinaryTable = new int[] { 1101 };

int BinaryTable = new int[] { 1,1,0,1 };

不知道怎么改。

【问题讨论】:

  • int[] BinaryTable?
  • 我必须从二进制值数到十进制数。
  • 您需要向我们提供更多信息。您的问题没有包含有关您要做什么的足够信息。请编辑您的问题以帮助解释您正在尝试做什么以及您为尝试自己解决此问题而采取的步骤。请参考stackoverflow.com/help/how-to-ask
  • 1101 二进制是13;你想把 13 个整数转换成 [1, 1, 0, 1] 数组吗?
  • 我想将样本二进制值转换为数组中的十进制值;

标签: c# arrays divide


【解决方案1】:
int[] BinaryTable = new int[] { 1101 };
List<int[]> allItems = new List<int[]>();
foreach (var item in BinaryTable)
{
    var items = item.ToString().Select(y => int.Parse(y.ToString())).ToArray();
    allItems.Add(items);
}

var final = allItems.SelectMany(x => x).ToArray();

【讨论】:

    【解决方案2】:

    你可以这样做:

    var bits = BinaryTable.Select(b => 
                     b.ToString().
                     Select(r => r == '0'  ? 0 : 1))
                  .SelectMany(x => x);
    

    如果你想从这里获得,这很有效

    [1101,11] → [1,1,0,1,1,1]

    。目前还不清楚你到底想要什么。而且这个解决方案不会检查您的输入是否真的只包含 1 和 0 数字,因为它是整数,理论上可以包含每个数字。

    【讨论】:

      【解决方案3】:

      又快又脏LINQ:

       int value = 1101; // a bit strange representation 
      
       int[] BinaryTable = value
         .ToString()
         .Select(c => c - '0')
         .ToArray();
      

      或者因为13 == 1101 binary:

        int value = 13; // just an integer
      
        int[] BinaryTable = Convert.ToString(value, 2)
          .Select(c => c - '0')
          .ToArray();
      

      如果您想将一个 array 转换为另一个 array,请使用 SelectMany 而不是 Select

        int[] source = new int[] {1101};
      
        int[] BinaryTable = source
          .SelectMany(value => value.ToString()
            .Select(c => c - '0')) 
          .ToArray();
      

      或者 int[] source = new int[] {13};

        int[] BinaryTable = source
          .SelectMany(value => Convert
             .ToString(value, 2)
             .Select(c => c - '0')) 
          .ToArray();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-22
        相关资源
        最近更新 更多