Java - 将字符串转换为相应的ascii的int? [英] Java - Convert a String of letters to an int of corresponding ascii?
问题描述
我想将一个字符串转换成一个带有相应ascii的int,假设abc
:在本例中, 979899
。
I want to convert a String, lets say "abc"
, to an int with the corresponding ascii: in this example, 979899
.
我遇到两个问题:
1)我只写了什么适用于ascii长两个字符且
1) what I wrote only works for characters whose ascii is two characters long and
2)的字符,因为这些数字非常大,我不能使用longs而且我在使用BigIntegers时遇到了麻烦。
2) since these numbers get very big, I can't use longs and I'm having trouble utilizing BigIntegers.
这是我到目前为止:
BigInteger mInt = BigInteger.valueOf(0L);
for (int i = 0; i<mString.length(); i++) {
mInt = mInt.add(BigInteger.valueOf(
(long)(mString.charAt(i)*Math.pow(100,(mString.length()-1-i)))));
}
任何建议都会很棒,谢谢!
Any suggestions would be great, thanks!
推荐答案
首先使用 StringBuilder
进行所有连接,然后创建 BigInteger
结果出来了吗?这似乎比你现在做的要简单得多。
What's wrong with doing all the concatenation first with a StringBuilder
and then creating a BigInteger
out of the result? This seems to be much simpler than what you're currently doing.
String str = "abc"; // or anything else
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray())
sb.append((int)c);
BigInteger mInt = new BigInteger(sb.toString());
System.out.println(mInt);
这篇关于Java - 将字符串转换为相应的ascii的int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!