ADHD Productions - 1 year ago 51
C# Question

# Convert array/list to a binary number, based on value of list element: 0 or not 0

I receive an array/list of 4 numbers. First I want to convert this to an array of binaries, which is then converted to a decimal. (I learned, this is possible with the "aggregate" function.)
The binary values are used to assign true/false values to 4 variables based on the position in the array.
If the value of the element of the list = 0 then binary value = 0 = false, if the value <> 0 then the binary value =1 = true.

All 4 numbers are always positive. E.g.

{40 60 80 100} --> {1 1 1 1} --> 15(decimal)
--> position1 = True; position2 = True; position3 = True; position4 = True;

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

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

Thanks!

Solution I used:

``````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
``````

//2nd edit: added solution I used.

Just `Aggregate` the `int[]` or `List<int>` via Linq:

``````  int[] source = new int[] { 20, 0, 40, 80 };

int result = source.Aggregate(0, (a, x) => (a << 1) | (x == 0 ? 0 : 1));
``````

Test:

``````  // "1011 or 11 (decimal)"
Console.Write(String.Format("{0} or {1} (decimal)",
Convert.ToString(result, 2), result));
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download