Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Convert a String of letters to an int of corresponding ascii?

Tags:

java

ascii

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!

like image 856
Aaron Avatar asked Nov 15 '12 20:11

Aaron


People also ask

How do I convert letters to ASCII?

char character = 'a'; int ascii = (int) character; In your case, you need to get the specific Character from the String first and then cast it. char character = name. charAt(0); // This gives the character 'a' int ascii = (int) character; // ascii is now 97.

How do you convert letters to integers?

The method valueOf() of class String can convert various types of values to a String value. It can convert int, char, long, boolean, float, double, object, and char array to String, which can be converted to an int value by using the Integer. parseInt() method.

Can you change a string to an int in Java?

We can convert String to an int in java using Integer.parseInt() method. To convert String into Integer, we can use Integer.valueOf() method which returns instance of Integer class.


2 Answers

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);
like image 109
arshajii Avatar answered Sep 28 '22 23:09

arshajii


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
like image 35
Kent Avatar answered Sep 28 '22 23:09

Kent