-2

I have a string whose value is '12345678'. I want to assign this value to integer array like the first index of the array contains 1, the second index of array contains 2 so on. So when I write below code and execute then i received value 48 for 0 index and value 49 for second index, ascii value of my number. Declaration

int[] ArryDIReadValue = new int[DI_COUNT_CHANNEL];
string binary = Convert.ToString(portData, 2);

ArryDIReadValue = binary.Select(n => Convert.ToInt32(n)).ToArray();

Could someone please help to overcome this problem.

Shanu Mehta
  • 182
  • 1
  • 14
  • 1
    What about `binary.ToCharArray();` ? Afterwards you can parse each char to an int and paste them into your `ArryDIReadValue` array. – michip96 Jun 21 '17 at 07:31

3 Answers3

2
ArryDIReadValue = binary.Select(n => (n - '0')).ToArray();

Simple and fast.

n - is char. So, chars 0, 1, ... 9 has codes 30, 31, ... 39. So, to get int value, we need to substract from every code 30. And we know, 30 is code of char 0.

Backs
  • 24,430
  • 5
  • 58
  • 85
1

Try adding ToString() such as;

ArryDIReadValue = binary.Select(n => Convert.ToInt32(n.ToString())).ToArray();
ali
  • 1,301
  • 10
  • 12
1

Use char.GetNumericValue:

ArryDIReadValue = binary.Select(n => (int)char.GetNumericValue(n)).ToArray();
adjan
  • 13,371
  • 2
  • 31
  • 48