Reputation: 162
After a lot of searching, I am unable to find what i am looking for
I have 2 questions like:
String str = "Hello"
Now I want its value in long
072101108108111L
where Ascii
072 = H
101 = e
108 = l
108 = l
111 = o
makes Hello
.
How can I do this and then convert it back to string?
For example if I have a long value
072101108108111L
then how can I get back the string "Hello" in java?
here is where I am at:
I can get string to long like this
String str = "Hello";
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray())
sb.append((int)c);
BigInteger mInt = new BigInteger(sb.toString());
String valu = mIn.tostring();
but value is 72 for "H"; I want it to be 072 so that the result is 3 characters, so that it fits the function to convert back to String.
Any help plz
Upvotes: 1
Views: 3012
Reputation: 164
private static String longToString(String string) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < string.length(); i = i + 3) {
String substring = string.substring(i, i + 3);
char ch = (char) Integer.parseInt(substring);
sb.append(ch);
}
return sb.toString();
}
private static String stringToLong(String string) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < string.length(); ++i) {
int ch = (int) string.charAt(i);
if (ch < 100) {
if(ch<10)
{
sb.append('0');
}
sb.append('0').append(ch);
} else {
sb.append(ch);
}
}
return sb.toString();
}
Upvotes: 1
Reputation: 5629
Let me give you hint on how to start.
We can get the ascii character value using a for loop and append it to a string.
for(int i = 0; i < s.length(); ++i)
{
int ch = (int)s.charAt(i);
System.out.println(ch);
}
Prints
72
101
108
108
111
Now, you want to add a zero if it is less than 100
StringBuilder ans = new StringBuilder();
for(...){
...
if(ch < 100){
ans.append("0).append(ch);
}
}
Try using a String itself instead of a long.
String longValue = "072101108108111";
Now, you know that each letter is represented as 3 characters, split it by 3 characters each.
for(int i = 0; i < s.length; i += 3)
{
int ch = Integer.parseInt(s.substring(i, i + 3));//get the integer representation of the character
System.out.println((char)ch);
}
Upvotes: 2