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

1
  • 1
    What about binary.ToCharArray(); ? Afterwards you can parse each char to an int and paste them into your ArryDIReadValue array. Commented Jun 21, 2017 at 7:31

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I wondered how it works. can you please explain how it is working.
1

Try adding ToString() such as;

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

1 Comment

thanks..now it is working...
1

Use char.GetNumericValue:

ArryDIReadValue = binary.Select(n => (int)char.GetNumericValue(n)).ToArray();

3 Comments

This will works only when i declare double array like double [] ArryDIReadValue = binary.Select(n => char.GetNumericValue(n)).ToArray(); otherwise it gives error.
@PriyankaMehta I edited the answer. It just works as you want.
Thanks.... Its working now

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.