Sarah
Sarah

Reputation: 11

Conversion of a Char variable to an integer

why is the integer equivalent of '8' is 56 in C sharp? I want to convert it to an integer 8 and not any other number.

Upvotes: 1

Views: 235

Answers (3)

Rob
Rob

Reputation: 10258

56 is the (EDIT) Unicode value for the character 8 use:

Int32.Parse(myChar.ToString());

EDIT:

OR this:

        char myChar = '8';
        Convert.ToInt32(myChar);

Upvotes: 3

Alexei Levenkov
Alexei Levenkov

Reputation: 100630

The right way of converting unicode characters in C#/.Net is to use corresponding Char methods IsDigit and GetNumericValue (http://msdn.microsoft.com/en-us/library/e7k33ktz.aspx).

If you are absolutely sure that there will be no non-ASCII numbers in your input than ChaosPandion's suggestion is fine too.

Upvotes: 0

ChaosPandion
ChaosPandion

Reputation: 78292

You'll need to subtract the offset from '0'.

int zero = (int)'0'; // 48
int eight = (int)'8'; // 56
int value = eight - zero; // 8

Upvotes: 5

Related Questions