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

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

Barbara Streisand
Release: 2024-12-22 01:05:28
Original
712 people have browsed it

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

Java Hexadecimal String Conversion

Q: How can I transform a string, such as "testing123," into its hexadecimal representation in Java? Is the conversion back a similar reversal of the process?

A:

Conversion to Hexadecimal:

Utilize the following code snippet to convert a string to hexadecimal:

public String toHex(String arg) {
    return String.format("%040x", new BigInteger(1, arg.getBytes(/*YOUR_CHARSET?*/)));
}
Copy after login

Note: The optional parameter YOUR_CHARSET allows you to specify the charset used to encode the string.

Conversion Back to String:

The conversion back to a string from hexadecimal is more involved. Here's a breakdown of the steps:

  1. Parse the hexadecimal string into a BigInteger.
  2. Convert the BigInteger to a byte array using its toByteArray() method.
  3. Construct a String using the byte array and the desired charset via the constructor String(byte[], Charset).

Use the same arg.getBytes() approach from the conversion to hexadecimal, ensuring consistent charset handling.

The above is the detailed content of How to Convert a String to its Hexadecimal Representation 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