0

I'm working on a school assignment where I have to convert a 8 bit binary number to decimal. This is my code;

         private void btnCalculate_Click(object sender, EventArgs e)
        {
            string invoer = txtBoxInput.Text;

            // binair naar decimaal
            if (rdBtnBinair.Checked == true)
            {
                int invoerlengte = invoer.Length;
                double nieuwgetal = 0;
                for (int i = 0; i <= invoerlengte; i++)
                {
                    if (int.Parse(invoer.Substring(i, 1)) == 1)
                    {
                        nieuwgetal += Math.Pow(2,(i+1));
                    }
                }
                txtBoxOutput.Text = nieuwgetal.ToString();

In C#. Error im getting: System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.

Think my code should be good, don't see whats wrong. Regards

2 Answers 2

1

You probably want to change this:

for (int i = 0; i <= invoerlengte; i++)

to this:

for (int i = 0; i < invoerlengte; i++)

Because when i is equal to invoer.Length then the next line of code will be looking for the next character after the end of the string, which is out of range:

invoer.Substring(i, 1)
Sign up to request clarification or add additional context in comments.

1 Comment

Just started typing this exact answer when yours came up.
0

Its because your foreach loops one iteration too much, because you use <= instead of '<'.

In these cases its always good to check what happens when. You can do this with a debugger, or plain old Console.WriteLine (or debug.log w/e)

online sample: https://dotnetfiddle.net/UyE2rw

    public static void Main()
    {
        var invoer = "12345";
        int invoerlengte = invoer.Length;
                double nieuwgetal = 0;
                for (int i = 0; i <= invoerlengte; i++)
                {
                    Console.WriteLine("i: " + i + ", substring: " + invoer.Substring(i, 1));

                    if (int.Parse(invoer.Substring(i, 1)) == 1)
                    {
                        nieuwgetal += Math.Pow(2,(i+1));
                    }
                }

    }

outputs:

i: 0, substring: 1
i: 1, substring: 2
i: 2, substring: 3
i: 3, substring: 4
i: 4, substring: 5
Run-time exception (line 13): Index and length must refer to a location within the string.
Parameter name: length

Stack Trace:

[System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.
Parameter name: length]
   at System.String.Substring(Int32 startIndex, Int32 length)
   at MyApp.Main() :line 13

and be mindful - indexes start at 0, counting at 1. So substring(0,1) is a char at index 0, but is the first element (char) in the string array.

item1 is at index0, item2 is at index1 etc.

De groetjes!

Comments

Your Answer

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