问题
I want to convert a String, lets say "abc", to an int with the corresponding ascii: in this example, 979899.
I've run into two problems:
1) what I wrote only works for characters whose ascii is two characters long and
2) since these numbers get very big, I can't use longs and I'm having trouble utilizing BigIntegers.
This is what I have so far:
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!
回答1:
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);
回答2:
you don't have to play the number game. (pow 100 etc). just get the number string, and pass to constructor.
final String s = "abc";
String v = "";
final char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
v += String.valueOf((int) chars[i]);
}
//v = "979899" now
BigInteger bigInt = new BigInteger(v); //BigInteger
BigDecimal bigDec = new BigDecimal(v); // or BigDecimal
回答3:
To handle n-digit numbers, you will have to multiply by a different power of ten each time. You could do this with a loop:
BigInteger appendDigits(BigInteger total, int n) {
for (int i = n; i > 0; i /= 10)
total = total.multiply(10);
return total.plus(new BigInteger(n));
}
However, this problem really seems to be about manipulating strings. What I would probably do is simply accumulate the digits int a string, and create a BI from the String at the end:
StringBuilder result = new StringBuilder();
for (char c : mString.getBytes())
result.append(String.valueOf(c));
return new BigInteger(result.toString());
来源:https://stackoverflow.com/questions/13405855/java-convert-a-string-of-letters-to-an-int-of-corresponding-ascii