我在c#中有一个char:
char foo = '2';
Run Code Online (Sandbox Code Playgroud)
现在我想把2变成一个int.我发现Convert.ToInt32返回char的实际十进制值而不是数字2.以下将起作用:
int bar = Convert.ToInt32(new string(foo, 1));
Run Code Online (Sandbox Code Playgroud)
int.parse也适用于字符串.
C#中没有本地函数从char到int而不是字符串吗?我知道这是微不足道的,但似乎很奇怪,直接进行转换没有任何原生的东西.
Jer*_*ten 147
这会将它转换为int:
char foo = '2';
int bar = foo - '0';
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为每个字符在内部由数字表示.字符"0"到"9"由连续数字表示,因此找到字符"0"和"2"之间的差异会得到数字2.
Cha*_*ant 122
有趣的答案,但文档说不同:
使用这些
GetNumericValue方法将Char表示数字的对象转换为数值类型.使用Parse和TryParse将字符串中的字符转换为Char对象.使用ToString一个转换Char对象的String对象.
http://msdn.microsoft.com/en-us/library/system.char.aspx
fau*_*lty 73
有没有人考虑使用int.Parse()和int.TryParse()喜欢这个
int bar = int.Parse(foo.ToString());
Run Code Online (Sandbox Code Playgroud)
甚至更好
int bar;
if (!int.TryParse(foo.ToString(), out bar))
{
//Do something to correct the problem
}
Run Code Online (Sandbox Code Playgroud)
它更安全,更不容易出错
son*_*tek 27
char c = '1';
int i = (int)(c-'0');
Run Code Online (Sandbox Code Playgroud)
你可以用它创建一个静态方法:
static int ToInt(this char c)
{
return (int)(c - '0');
}
Run Code Online (Sandbox Code Playgroud)
试试这个
char x = '9'; // '9' = ASCII 57
int b = x - '0'; //That is '9' - '0' = 57 - 48 = 9
Run Code Online (Sandbox Code Playgroud)
原则:
char foo = '2';
int bar = foo & 15;
Run Code Online (Sandbox Code Playgroud)
ASCII 字符 0-9 的二进制是:
0 - 0011 0000
1 - 0011 0001
2 - 0011 0010
3 - 0011 0011
4 - 0011 0100
5 - 0011 0101
6 - 0011 0110
7 - 0011 0111
8 - 0011 1000
9 - 0011 1001
Run Code Online (Sandbox Code Playgroud)
如果你把它们中的每一个都取前 4 个 LSB(使用按位 AND 和 8'b00001111 等于 15)你得到实际数字(0000 = 0,0001=1,0010=2,...)
用法:
public static int CharToInt(char c)
{
return 0b0000_1111 & (byte) c;
}
Run Code Online (Sandbox Code Playgroud)
小智 6
真正的方法是:
int theNameOfYourInt = (int).Char.GetNumericValue(theNameOfYourChar);
"theNameOfYourInt" - 您希望将字符转换为的 int。
"theNameOfYourChar" - 您要使用的 Char,以便将其转换为 int。
留下一切。
我同意@Chad Grant
如果您转换为字符串也是正确的,那么您可以将该值用作问题中所说的数字
int bar = Convert.ToInt32(new string(foo, 1)); // => gives bar=2
Run Code Online (Sandbox Code Playgroud)
我试图创建一个更简单易懂的例子
char v = '1';
int vv = (int)char.GetNumericValue(v);
Run Code Online (Sandbox Code Playgroud)
char.GetNumericValue(v) 返回双精度值并转换为 (int)
更高级的数组用法
int[] values = "41234".ToArray().Select(c=> (int)char.GetNumericValue(c)).ToArray();
Run Code Online (Sandbox Code Playgroud)