Wednesday, April 24, 2024
HomeJavaMethods to Convert and Print Byte array to Hex String in Java?...

Methods to Convert and Print Byte array to Hex String in Java? Instance


We frequently must convert byte arrays to Hex String in Java, With a view to print byte array contents in a readable format. Since many cryptographic algorithms e.g. MD5 return the hash worth as a byte array, With a view to see and examine that byte array, you must convert the byte array to Hex String. As we now have seen, whereas producing MD5 checksum of File, there are a number of methods to convert byte array to Hexadecimal String in Java. You possibly can both write your individual methodology, or you should use an open-source library e.g. Apache commons-codec to create Hex String from a byte array in Java. Commons codec offers a utility class Hex, which incorporates an encodeHexString() methodology to create Hex String from a byte array.

It is the most effective choices to generate
Hex String if you happen to are already utilizing this library to generate MD5 hash values. On this Java tutorial, we are going to see what’s the challenge with printing byte array as regular String, and a couple of examples to transform a byte array into Hexadecimal String in Java.


The problem with Printing Byte arrays as String

How to convert and Print byte array to Hex String in Java with ExampleA few of you is likely to be questioning, why cannot we use String constructor which accepts byte array e.g. new String(byte[]). Nicely, the true challenge with printing byte array is non-printable ASCII characters.  Your MD5 checksum or any byte array might include some non-printable characters, which implies you cannot examine two-byte arrays by their String illustration. 

By the best way, this isn’t an issue if you are encoding String in base64, as they solely use printable ASCII characters. In our code instance of printing byte array as regular String, you possibly can see completely different strings, generated from completely different byte arrays, seems the identical. 


Since 0, 5 and 6 signify non-printable characters ASCII characters NUL, ENQ and ACK, they’re exhibiting right here as white area here. This challenge could be resolved if we convert byte array to Hexadecimal String, after which print or show it.

Advantages of Printing Byte array as Hex String in Java

There are a few advantages of printing byte array as Hex String in Java. In truth, displaying byte array as Hex String is regular apply, particularly once you wish to see and examine MD5 hash or digest worth, generated by the cryptographic algorithm.

1) It is simple to show contents of byte array in a typical method, as byte array might include non-printable characters.

2) Hex String permits you to shortly examine two-byte arrays contents.

3) Hex String is simple to learn, in comparison with binary or decimal format because it takes fewer digits.

These are some notable advantages of printing byte array as a hex string in Java.



2 methods to Convert Byte Array to Hex String in Java

As I mentioned, there are a number of methods to generate hexadecimal String from byte array in Java e.g. together with image array, and using the String format methodology. On this Java program, we are going to see two examples to transform byte array to Hexadecimal String. 


Within the first instance, we now have used core Java, and within the second instance, we now have used Apache commons-codec library. It offers a utility class org.apache.commons.codec.binary.Hex, which might convert byte array to Hex String in Only one line


I’m massive fan of utilizing open supply libraries, particularly for manufacturing utilization. By the best way, we may even look challenge with printing byte array as regular String, which can assist you to grasp want of changing byte array to Hex String earlier than printing them.
import java.util.logging.Logger;
import org.apache.commons.codec.binary.Hex;

/**
 * Java program to transform Byte array to Hex String in Java.
 * This Java instance makes use of core Java and Apache commons code to
 * generate Hexadecimal String from byte array in Java.
 *
 * @writer Javin Paul
 */
public class ByteArrayToHexString {
    non-public static remaining Logger logger = Logger.getLogger(StringReplace.class.getName());
    
    public static void principal(String args[]) {
       
       //byte array with non printable characters 
       byte[] bytes = new byte[]{'a', 'b', 0, 5, 'c','d'};
       byte[] nonprintable = new byte[]{'a', 'b', 0, 6, 'c','d'};
     
       //You cannot print byte array as String as a result of they could include non printable
       //characters e.g. 0 is NUL, 5 is ENQ and 6 is ACK in ASCII format
      
       String worth = new String(bytes);
       System.out.println(worth);      
       String str = new String(nonprintable);
       System.out.println(str);   
      
       //Changing byte array to Hex String in Java for printing
       System.out.println("Byte array to Hex String in Java :                       " 
                                   + bytesToHexString(bytes));     
      
       //Apache commons codec to transform byte array to Hex String in Java
       String hex = Hex.encodeHexString(bytes);
       System.out.println("Byte array to Hexadecimal String utilizing Apache commons:   " 
                                  + hex);
    }
   
    public static String bytesToHexString(byte[] bytes){
        StringBuilder sb = new StringBuilder();
        for(byte b : bytes){
            sb.append(String.format("%02x", b&0xff));
        }
        return sb.toString();
    }  
   
}

Output:
ab  cd
ab  cd
Byte array to Hex String in Java :                       616200056364
Byte array to Hexadecimal String utilizing Apache commons:   616200056364

As I defined within the part challenge with printing byte arrays, character after “ab” will not be white area, it is a NUL ASCII character, however exhibiting as white area right here. Attempt working this Java program in your machine, and copying the primary line of output, you possibly can solely copy the primary two characters.

That is all on Methods to convert byte array to Hex String in Java. As I mentioned, the byte array might include some non-printable characters, which can produce a deceptive worth whereas printing them as regular String. It is all the time finest to show the contents of the byte array as a hex string in Java.

Associated  Java String Tutorials from Javarevisited Weblog



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments