Home >Java >javaTutorial >How to Convert a String to Hexadecimal and Back in Java?

How to Convert a String to Hexadecimal and Back in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-07 21:17:15191browse

How to Convert a String to Hexadecimal and Back in Java?

Converting a String to Hexadecimal in Java

When working with binary data or cryptography, converting a string to its hexadecimal representation becomes essential. In Java, this conversion process can be accomplished using the String class and the BigInteger class.

To convert a string to hexadecimal, you can use the following steps:

  1. Convert the string to a byte array using the getBytes() method:

    byte[] bytes = myString.getBytes(/*YOUR_CHARSET?*/);
  2. Use the BigInteger constructor to create a new BigInteger object from the byte array:

    BigInteger bi = new BigInteger(1, bytes);
  3. Use the format() method of the String class to format the BigInteger object as a hexadecimal string:

    String hexString = String.format("%040x", bi);

The resulting hexString will be a 40-character hexadecimal representation of the original string.

Converting a Hexadecimal String Back to a String

The process of converting a hexadecimal string back to a string is similar to the above process, but in reverse.

  1. Convert the hexadecimal string to a BigInteger object using the BigInteger constructor:

    BigInteger bi = new BigInteger(hexString, 16);
  2. Use the getBytes() method of the BigInteger class to convert the BigInteger object to a byte array:

    byte[] bytes = bi.getBytes();
  3. Use the String constructor to create a new String object from the byte array:

    String myString = new String(bytes);

The resulting myString will be the original string that was converted to hexadecimal.

The above is the detailed content of How to Convert a String to Hexadecimal and Back in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn