char(数字) 转换 int

本文探讨了在Java中将char类型的数字转换为int进行计算时遇到的问题。直接转换会得到ASCII码而非预期数值。文中提出了三种解决方案:通过ASCII运算、使用Character.getNumericValue()和Integer.parseInt(),并进行了性能测试。方法一最快,方法三最慢。

         刷题遇到一个考点是 char型数字 转 int 进行计算的问题。一看就会,一做就错,显然是在这里的认识薄弱了。将一番搜索的结果记录下来,以备再忘来打脸。

        char的定义参考:Java基本数据类型之char

        首先,char  跟 int 这两种类型可以直接互转:

char ch1 = 'a';
int i = ch1;
char ch2 = (char)i;

         那么面对 char in = ‘2’  需要转成 int 做计算,那么很自然想到把char 型变量直接赋给 int 型就能计算 了。

char in = '2';
int iVar = in;
System.out.println(in);
System.out.println(iVar);

//输出:
// 2
// 50

        想当然的做法果然错了:期望取出来的 int 2,实际却是 int 50。

        当 char 直接 赋给 int 时,实际上是把 char 变量的ASCII 码赋给 int类型,因此取出char 变量的数值不能通过直接转换成int的方法实现。

方法一:

        利用char变量使用 ASCII进行算术运算这一特征,可以得到一种间接计算获取数值的方法。

char ch1 = '8';
int iVar = ch1 - '0';
System.out.println(iVar);

//输出
// 8

'0'-'9'  ASCII 为 48-57,且顺序一致,因而char数字之间的差值等于数字之间的差值 。

System.out.println('9'-'1' == 9-1);	//true
System.out.println('8'-'0' == 8);	//true

方法二:

        使用 char 包装类Character提供的方法;

char ch1 = '8';
Character.getNumericValue(ch1);    // 8
//Character.digit(ch1,10);    // 8

方法三:

        通过int 包装类 Integer 。

char ch2 = '8';
int i = Integer.parseInt(String.valueOf(ch2));    // 8

方法一最快,方法三慢。测试代码如下:

    @Test
	public void test(){
		int circle = 100000;
		StopWatch watch = new StopWatch();
		char ch1 = '8';
		watch.start("task1");
		int count = 0;
		while (count++ < circle){
			int i = ch1 - '0';
		}
		watch.stop();
		watch.start("task2");
		count = 0;
		while (count++ < circle){
			int i = Character.digit(ch1,10);
		}
		watch.stop();

		watch.start("task3");
		count = 0;
		while (count++ < circle){
			int i = Integer.parseInt(String.valueOf(ch1));
		}
		watch.stop();
		System.out.println(watch.prettyPrint());
	}



结果:
---------------------------------------------
ns         %     Task name
---------------------------------------------
002761400  010%  task1
003343100  012%  task2
022454000  079%  task3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

oStartflying

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值