Lucas Hirtzbruch
Lucas Hirtzbruch

Reputation: 23

System.OverflowException, and how to fix it

I was making a fake encryption program and when trying to convert a string into a int32 and i get the following message System.OverflowException. The error message is at the Convert.ToInt32(textnumbers);

 static void encryption(string text)
    {
        byte[] nums = Encoding.ASCII.GetBytes(text);
        int[] en = new int[nums.Length];

        for (int i = 0; i < nums.Length; i++)
        {

            en[i] = nums[i] * 2 + 5;

        }

        string textnumbers = string.Join("", en);
        Console.WriteLine(textnumbers);

        int num = Convert.ToInt32(textnumbers);

        string hexValue = num.ToString("x");
        Console.WriteLine(hexValue);

    }
    static void Main(string[] args)
    {

        encryption("abcde");
        Console.ReadLine();

    }

Upvotes: 1

Views: 9149

Answers (2)

John H
John H

Reputation: 14640

The important part is to pay attention to the exception message that the System.OverflowException produces, which is:

Value was either too large or too small for an Int32.

That gives you a big clue as to what the problem is.

Next, if you take a look at the value of textnumbers after the for loop has been completed, you'll see its value is 199201203205207. As Çöđěxěŕ mentioned, the maximum value a signed 32-bit integer can store is 2147483647, so the exception is telling you a 32-bit integer isn't large enough to store the value you want.

To fix this, you can use a 64-bit integer:

long num = Convert.ToInt64(textnumbers);

long represents a signed 64-bit integer, and can store values in the range -9223372036854775808 to 9223372036854775807, inclusive, which can comfortably store 199201203205207.

If ever you need to know the range of values a numeric type can represent, you can examine its MinValue and MaxValue properties (e.g. int.MinValue, or long.MaxValue).

One thing though: you should learn to work with the debugger, because it makes fixing this kind of problem by yourself trivial. It's worth investing that time so you can self-service problems like this, without relying on others.

Upvotes: 2

Sina Hoseinkhani
Sina Hoseinkhani

Reputation: 328

Your program generates '199201203205207' which is greater than what you could fit in int. try changing it to long ,also use Convert.ToInt64(textnumbers):

static void encryption(string text)
{
    byte[] nums = Encoding.ASCII.GetBytes(text);
    int[] en = new int[nums.Length];

    for (int i = 0; i < nums.Length; i++)
    {

        en[i] = nums[i] * 2 + 5;

    }

    string textnumbers = string.Join("", en);
    Console.WriteLine(textnumbers);

    long num = Convert.ToInt64(textnumbers);

    string hexValue = num.ToString("x");
    Console.WriteLine(hexValue);

}

static void Main(string[] args)
{

    encryption("abcde");
    Console.ReadLine();

}

Upvotes: 0

Related Questions