0

I'm writing a program to convert numbers in an array znaky to array in binary numbers called binary, but it returns me error.

System.IndexOutOfRangeException: Index was outside the bounds of the array.

char[] znaky = new char[moje.Length];                                                                                                                                                                 
for (int i = 0; i < znaky.Length; i++)
{                                                                                          
    znaky[i] = moje[i];                                                                         
}

string binary = "";
foreach (int a in znaky)
{
    binary += Convert.ToString(znaky[a], 2);  
}

In array moje was the numbers, but for me I change his positions. In this program I change words to binary code.

4
  • As a suggestion, next time use english names for variables when asking on SO Commented May 24, 2018 at 13:55
  • And the second foreach should be a for: for (int a = 0; a < znaky.Length; a++) Commented May 24, 2018 at 13:56
  • 1
    Or just use a directly instead of znaky[a]. But wait, znaky is a char array? Does it need to be? Commented May 24, 2018 at 13:57
  • Can you show us the code before this? What is moje and how is it populated? Is moje a char[]? In which case why are you copying it to znaky? Commented May 24, 2018 at 14:24

1 Answer 1

3

Second foreach should be a for:

for (int a = 0; a < znaky.Length; a++)

OR keep the foreach and then change the Convert:

Convert.ToString(a, 2);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.