5

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!

arshajii
  • 127,459
  • 24
  • 238
  • 287
Aaron
  • 614
  • 3
  • 10
  • 16
  • Don't cast to long again. Did you try removing long cast? – kosa Nov 15 '12 at 20:43
  • The parameter of valueOf() is long, so I have to. – Aaron Nov 15 '12 at 20:46
  • 2
    Instead of valueOf(), just use Constructor, new BigInteger(String.valueOf(yourCode));http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigInteger.html#BigInteger(java.lang.String) – kosa Nov 15 '12 at 20:47

3 Answers3

5

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);
arshajii
  • 127,459
  • 24
  • 238
  • 287
1

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
Kent
  • 189,393
  • 32
  • 233
  • 301
  • Assuming the string `s` is going to be long, it would probably be better to use a `StringBuilder` performance-wise. Repetitive string concatenations can be expensive. – arshajii Nov 15 '12 at 21:01
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());
mdgeorge
  • 350
  • 2
  • 11