2008-10-27 87 views
93

所以我在C#中的字符:C#的char詮釋

char foo = '2'; 

現在我想要得到的2成一個int。我發現Convert.ToInt32返回字符的實際十進制值,而不是數字2下面的工作:

int bar = Convert.ToInt32(new string(foo, 1)); 

int.parse僅適用於字串。

在C#中沒有本地函數從char到int而沒有使其成爲字符串?我知道這是微不足道的,但看起來很奇怪,沒有直接進行轉換的原生東西。

回答

91

有趣的答案,但該文檔說是不同的:

使用GetNumericValue方法 轉換Char對象,表示 一個數字一個數字值類型。使用 ParseTryParse將字符串中的 字符轉換爲Char 對象。使用ToStringChar 對象轉換爲String對象。

http://msdn.microsoft.com/en-us/library/system.char.aspx

103

這將其轉換爲int:

char foo = '2'; 
int bar = foo - '0'; 

這工作,因爲每個字符內部有一個數字來表示。字符「0」至「9」由連續的數字來表示,所以找到字符「0」和「2」的結果之間的差的數量2.

+0

更重要的是,它爲什麼被低估? – 2008-10-27 04:57:04

+0

它的工作原理是因爲0是48. – sontek 2008-10-27 04:57:47

+3

Downvoting,因爲我只能看到機制,而不是意圖。 – 2008-10-27 05:39:23

22
char c = '1'; 
int i = (int)(c-'0'); 

並且可以營造一個靜態方法它:

static int ToInt(this char c) 
{ 
    return (int)(c - '0'); 
} 
58

具有使用int.Parse()int.TryParse()這樣

int bar = int.Parse(foo.ToString()); 

更妙的是這樣

人認爲
int bar; 
if (!int.TryParse(foo.ToString(), out bar)) 
{ 
    //Do something to correct the problem 
} 

這是一個很大安全和減少錯誤

8

嘗試這個

char x = '9'; // '9' = ASCII 57 

int b = x - '0'; //That is '9' - '0' = 57 - 48 = 9 
7

默認情況下使用UNICODE,所以我建議使用錯誤的方法

int bar = int.Parse(foo.ToString());

即使下的數值是相同的數字和基本的拉丁字符。

-5

這爲我工作:

int bar = int.Parse("" + foo); 
2

把它轉換成整數,處理Unicode

CharUnicodeInfo.GetDecimalDigitValue('2')

你可以閱讀更多here

0

我使用Compact Framework 3.5,沒有「char.Parse」方法。 我認爲使用Convert類不錯。 (通過C#見CLR,傑弗裏裏希特)

char letterA = Convert.ToChar(65); 
Console.WriteLine(letterA); 
letterA = 'あ'; 
ushort valueA = Convert.ToUInt16(letterA); 
Console.WriteLine(valueA); 
char japaneseA = Convert.ToChar(valueA); 
Console.WriteLine(japaneseA); 

工程與ASCII字符或Unicode字符基於結果

那的一些方法都

安東尼

0

比較時,字符不是ASCII數字:

char c = '\n';        
Debug.Print($"{c & 15}");     // 10 
Debug.Print($"{c^48}");     // 58 
Debug.Print($"{c - 48}");     // -38 
Debug.Print($"{(uint)c - 48}");    // 4294967258 
Debug.Print($"{char.GetNumericValue(c)}"); // -1 
-3

我見過很多答案但他們似乎讓我感到困惑。我們不能簡單地使用類型鑄造。

對於離: -

int s; 
char i= '2'; 
s = (int) i; 
0
char foo = '2'; 
int bar = foo & 15; 

的ASCII charecters 0-9的二進制:

0 - 00110000

1 - 00110001

2 - 00110010

3 - 00110011

4 - 00110100

5 - 00110101

6 - 00110110

7 - 00110111

8 - 00111000

9 - 00111001

如果你在其中每個人中取前4個LSB(使用按位AND與8'b00001111等於15),你會得到實際的數字(0000 = 0,0001 = 1,0010 = 2,...)