In Java, is there a simple method to convert the format of a given string? For example, I have the string "test22". I'd like the binary value and hex value. As well as possibly the ascii values of each character?
views:
154answers:
1
+2
A:
My solution would be to take the String, convert it to a char array, and then convert the integer values of the char array into binary or hex through the Integer.toBinaryString() or Integer.toHexString() or Integer.toOctalString() if you would like.
just replace binary string with hex and the function will do the same thing
public String convertToBinary(String str){
char [] array = str.toCharArray();
String binaryToBeReturned = "";
for(int i=0;i<str.length();i++){
binaryToBeReturned += Integer.toBinaryString((int)array[i]) + " ";
}
return binaryToBeReturned;
}
Also to get the ASCII values of the String int value = (int)string.charAt(i);
will get the ASCII value.
I added a space just for formatting, not sure how you needed it formatted, and this is just a simple implementation.
Grue
2010-04-09 01:26:24