How can (byte)Convert.ToChar(anyStringOfLengthOne) possibly throw an error?

We have this rather simple code in a project:

string input = "Any string";
for (int i = 0; i < input.Length; i++)
{
    string stringOfLengthOne = input.Substring(i, 1);
    byte value = (byte)Convert.ToChar(stringOfLengthOne);
    if (value == someValue)
    {
        // do something
    }
}

The input is a string with characters usually read from a file that need to be processed depending on their byte value.

Unfortunately, we do not have the chance to debug this process step-by-step, we just need to make an educated guess what kind of string could cause

 (byte)Convert.ToChar(anyStringOfLengthOne)

in the code above to throw an "Arithmetic operation resulted in an overflow" error.

My thinking is that as soon as I have a string, it should always be possible to 1. pick a char and 2. convert it to a byte. Yet the error occurs.

Any ideas, hints? Or can someone even provide a string that throws this kind of error?

Answers


Characters in .Net are 16 bits (short/ushort) in length.

The default project settings for C# means that the cast would work and will just ignore the higher bits for any character that is larger than 255, i.e. like using (byte) (c & 0xff).

However, if you are using checked arithmetic, trying to cast a char that is greater than 255 will result in an ArithmeticOverflowExcetion.

The default setting for arithmetic can be set to checked/unchecked in the project's build settings.

Example

char c = (char) 300;
byte b = unchecked ((byte) c);
Console.WriteLine (b);

// Result: 44

char c = (char) 300;
byte b = checked ((byte) c);
Console.WriteLine (b);

// Result: ArithmeticOverflowExcetion

Alternative

Alternativly, you could compare the characters directly.

For example to test if a character is 0-9

char c = input[i];
if (c >= '0' && c <= '9') {
    // do something
}

You can even compare a char to an int

char c = input[i];
if (c >= 48 && c <= 57) {
    // do something
}

Need Your Help

Sort ordering in Django: possible to ignore “The” prefix when sorting?

django sorting

This seems like the kind of thing Django makes simple, wondering if anyone has any experience with it.

how to add title to navigation drawer in android

android xml android-layout

I have created a navigation drawer having a listview with icon and text. Now, I want to add a title above it and also another below it. Below are two xml I have used: