Java:从char中减去'0'得到一个int ...为什么这个工作? [英] Java: Subtract '0' from char to get an int... why does this work?

查看:229
本文介绍了Java:从char中减去'0'得到一个int ...为什么这个工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很好用:

int foo = bar.charAt(1) - '0';

然而这不是 - 因为bar.charAt(x)返回一个char:

Yet this doesn't - because bar.charAt(x) returns a char:

int foo = bar.charAt(1);

似乎从char中减去'0'会将其转换为整数。

It seems that subtracting '0' from the char is casting it to an integer.

为什么或如何减去字符串'0'(或者它是char?)将另一个char转换为整数?

Why, or how, does subtracting the string '0' (or is it a char?) convert another char in to an integer?

推荐答案

这是一个聪明的伎俩。 char实际上与短裤的类型/长度相同。现在当你有一个表示ASCII / unicode数字(如'1')的字符,并从中减去最小的ASCII / unicode数字(例如'0'),那么你将留下数字的相应值(因此,1)

That's a clever trick. char's are actually of the same type / length as shorts. Now when you have a char that represents a ASCII/unicode digit (like '1'), and you subtract the smallest possible ASCII/unicode digit from it (e.g. '0'), then you'll be left with the digit's corresponding value (hence, 1)

因为char与short相同(尽管是无符号的short),所以可以安全地将它转换为int。如果涉及算术,则铸件总是自动完成

Because char is the same as short (although, an unsigned short), you can safely cast it to an int. And the casting is always done automatically if arithmetics are involved

这篇关于Java:从char中减去'0'得到一个int ...为什么这个工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆