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
Release: 2024-12-07 21:17:15
Original
190 people have browsed it

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?*/);
    Copy after login
  2. Use the BigInteger constructor to create a new BigInteger object from the byte array:

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

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

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);
    Copy after login
  2. Use the getBytes() method of the BigInteger class to convert the BigInteger object to a byte array:

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

    String myString = new String(bytes);
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template