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!