Showing posts with label Convert string to ASCII value in java. Show all posts
Showing posts with label Convert string to ASCII value in java. Show all posts

Thursday, May 9, 2013

[android help] Convert string to ASCII value in java

android - Convert string to ASCII value in java - Stack Overflow








Tell me more ×

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

















I have


String name = "admin";


then i do


String char = name.substring(0,1); //char="a"


I want to convert the char to it's ASCII value (97), how can i do this in java?


























Instead of this:



String char = name.substring(0,1); //char="a"


You should use the charAt() method.



char c = name.charAt(0); // c='a'
int ascii = (int)c;






















Very simple. Just cast your char as an int.



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. Though cast is not required explicitly, but its improves readability.



int ascii = character; // Even this will do the trick.
























Just cast the char to an int.



char character = 'a';
int number = (int) character;


The value of number will be 97.






















It's simple, get the character you want, and convert it to int.



String name = "admin";
int ascii = name.charAt(0);
























Convert the char to int.



String name = "admin";
int ascii = name.toCharArray()[0];


Also :



int ascii = name.charAt(0);





















If you wanted to convert the entire string into concatenated ASCII values then you can use this -



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);


wherein you will get 979899 as output.


Credit to this.


I just copied it here so that it would be convenient for others.






















just a different approach



String s = "admin";
byte[] bytes = s.getBytes("US-ASCII");


bytes[0] will represent ascii of a.. and thus the other characters in the whole array.




















lang-java







.

stackoverflow.comm

Google Voice on T-Mobile? [General]

Google Voice on T-Mobile? So I recently switched from a GNex on Verizon to a Moto X DE on T-Mobile. I had always used Google Voice for my v...