android字符串换算int,【已解决】android中的java中的string转int

本文探讨了如何在Java中处理字符串转换,重点在于将0x前缀的十六进制字符串(如"0x123")转换为整数。首先尝试使用`Integer.parseInt()`失败,随后介绍了`Integer.decode()`方法的使用,以解决0x形式的十六进制字符串转int的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【问题】

需要将一个字符串,可能是十进制:

比如

123

也可能是16进制:

0x123

转换为int值。

【折腾过程】

1.参考:

去试试,void strToIntTest(){

String testStr1 = "123";

String testStr2 = "0x123";

int convertedIntValue1 = Integer.parseInt(testStr1);

int convertedIntValue2 = Integer.parseInt(testStr2);

System.out.println("convertedIntValue1=" + convertedIntValue1 + ", convertedIntValue2=" + convertedIntValue2);

}

应该就可以了。

结果调试发现:int convertedIntValue2 = Integer.parseInt(testStr2);

会挂掉。

2.然后自己去试试,通过自带文档,发现有个decode:

b816c6be391b6f1643866ebc5c88ddc6.png

然后去试试:void strToIntTest(){

String testStr1 = "123";

String testStr2 = "0x456";

int convertedIntValue1 = Integer.parseInt(testStr1);

//int convertedIntValue2 = Integer.parseInt(testStr2);

int convertedIntValue2 = Integer.decode(testStr2);

System.out.println("convertedIntValue1=" + convertedIntValue1 + ", convertedIntValue2=" + convertedIntValue2);

}

结果,虽然工作了。

却又遇到:

【总结】

直接调用

Integer.parseInt

即可将string转为int,但是不支持0x123的形式。

最后去用:

Integer.decode("0x123");

才可以。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值