5

我想将字符串转换为"abc"具有相应 ascii 的 int:在此示例中,979899.

我遇到了两个问题:

1) 我写的内容只适用于 ascii 长度为两个字符的字符,并且

2) 由于这些数字变得非常大,我不能使用 long,而且我在使用 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)))));
}

任何建议都会很棒,谢谢!

4

3 回答 3

5

首先用 a 进行所有连接StringBuilder然后BigInteger从结果中创建 a 有什么问题?这似乎比您目前所做的要简单得多。

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);
于 2012-11-15T20:55:23.567 回答
1

你不必玩数字游戏。(战俘 100 等)。只需获取数字字符串,然后传递给构造函数。

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
于 2012-11-15T20:56:33.447 回答
0

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());
于 2012-11-15T21:15:41.500 回答