0

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?

2
  • A tilde isn't hex or hexidecimal. Can you explain the combination of operations you are doing? Commented Sep 28, 2017 at 14:36
  • There is no such thing like 'hex number' (against int "decimal"). These are external forms of the same. When people will have 14 fingers, out base will be 14, but count of peaches in basker remain the same Commented Sep 28, 2017 at 14:36

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Worked! Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.