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

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

DDD
DDDOriginal
2024-11-21 16:34:12759browse

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);
}

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);

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();

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!

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