Home > Java > javaTutorial > body text

How to Preserve Leading Zeros When Converting Byte Arrays to Hex Strings in Java?

DDD
Release: 2024-11-21 16:34:12
Original
759 people have browsed it

How to Preserve Leading Zeros When Converting Byte Arrays to Hex Strings in Java?

Preserving Leading Zeros When Converting Byte Arrays to Hex Strings in Java

To convert a byte array to a hexadecimal digit string while maintaining leading zeros in Java, implement the following approaches:

Using String.format

Format each byte as a fixed-width two-character hexadecimal string using String.format. Leading zeros are guaranteed:

byte[] bytes = ...;
String hexString = "";
for (byte b : bytes) {
    hexString += String.format("%02X", b);
}
Copy after login

Using Apache Commons Codec

Take advantage of Apache Commons Codec's Hex.encodeHexString method:

import org.apache.commons.codec.binary.Hex;

byte[] bytes = ...;
String hexString = Hex.encodeHexString(bytes);
Copy after login

Using Guava's ByteString

Employ Guava's ByteString class to convert the bytes to a hex string:

import com.google.common.hash.Hashing;

byte[] bytes = ...;
String hexString = Hashing.sha256().hashBytes(bytes).toString();
Copy after login

Each approach ensures that leading zeros are preserved when converting byte arrays to hex strings.

The above is the detailed content of How to Preserve Leading Zeros When Converting Byte Arrays to Hex Strings 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template