Convert to decimal from array

I have an array as such:

int[] fourbits = new int[4];
fourbits[0] = neuroninputs.input1;
fourbits[1] = neuroninputs.input2;
fourbits[2] = neuroninputs.input3;
fourbits[3] = neuroninputs.input4;

Each element contains a binary value. For instance:

Console.WriteLine(fourbits[0]);   

outputs 1.

What I'm trying to do is take all the values ​​from this array (1010) and convert them to decimal and print that value (10).

+4
source share
1 answer

First connect all the bits with stringwith String.Join, then use the Convert.ToInt32method defining the parameter base.

var value = Convert.ToInt32(string.Join("", fourbits), 2);

Console.WriteLine(value);

Note. . You have to make sure that your array contains only onesand zerosso that the base parameter speficy is 2. Otherwise you will receive FormatException.

+3
source

Source: https://habr.com/ru/post/1533551/


All Articles