2016-09-15 3 views
1

4つの数値の配列/リストを受け取ります。最初に、これをバイナリの配列に変換し、それを小数に変換します。 (これは「集約」関数で可能です) バイナリ値は、配列内の位置に基づいて4つの変数に真偽値を割り当てるために使用されます。 リストの要素の値が0の場合、バイナリ値= 0 =偽、値が<> 0の場合、バイナリ値= 1 =真です。リスト要素の値に基づいて、配列/リストを2進数に変換します。0または0 0

4つの数字はすべて常に正です。例えば。

{40 60 80 100} - > {11111 - > 15(10進) - > position1 = True; position2 = True; position3 = True; position4 = True;

{20 0 40 80} - > {1 0 11 1} - > 11(10進) - > position1 = True; position2 = False; position3 = True; position4 = True;

{0 0 20 50} - > {0 0 1 1} - > 3(10進) -> position1 = False; position2 = False; position3 = True; position4 = True;

ありがとうございます!私が使用し

ソリューション:

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編集:私が使用追加ソリューション:第二編集//
の要求に、それはより具体的な作られました。 LINQの介し

+0

もっと具体的にしました。見つけて解決策を追加しました。 –

答えて

1

だけAggregateint[]又はList<int>

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)); 
0

別のオプションは、最初の実際のビット表現を構築し、小数に変換することである。

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

これは非常にシンプルで理解しやすい方法です:

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); 
関連する問題