简体   繁体   中英

Convert Integer to Hex in Java

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM