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!
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.
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.
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.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With