Reputation: 53
I want to convert an hex to int and back again.
Hex to int:
String input = "˜";
char charValue = new String(input.getBytes(), "ISO-8859-1").charAt(0);
int intValue = (int) charValue; //=152
String hexString = Integer.toHexString(intValue); //=98
Is it possible to get the ˜ back again?
Upvotes: 0
Views: 1369
Reputation: 533482
The ˜
isn't a tilde, it is character with unicode 732.
When you convert it to a byte[], you get two bytes if you use UTF-8, -53 and -100
However if you ignore the second one and convert it to a char
you get 152 (which is -53 & 0xFF)
You have a number of lossy transformations which makes it impossible to reverse them.
What you can do is convert the character to hexadecimal and back again.
String input = "˜";
String hex = DatatypeConverter.printHexBinary(input.getBytes("UTF-16BE"));
System.out.println("hex: "+hex);
String input2 = new String(DatatypeConverter.parseHexBinary(hex), "UTF-16BE");
System.out.println("input2: "+input2);
prints
hex: 02DC
input2: ˜
This will work for arbitrary Strings (of less than half a billion characters)
Upvotes: 2