Java – convert a byte to a string representation of a integer as an unsigned integer in base 16

This week I  had to fix a problem with a convertion of a byte array to a string representation of integers as unsigned integers in base 16. After spending the needed time I found that there are several solutions.

The problem:


 private static final int OFFSET = 0xFF;

 public static String getHexString(byte[] array) {
   StringBuffer hexString = new StringBuffer();
   for (int i = 0; i < array.length; i++) {
     String intBase16AsString = Integer.toHexString(OFFSET & array[i]);
     hexString.append(intBase16AsString);
   }
   return hexString.toString();
 }

At first glance, the first solution which rise up in your mind is to use Integer.toHexString() method. But when you test and after that read in the API that: “This value is converted to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0s. The problem is that the result string which you get is with a changable length. It is a problem if you use this string as a hash of password or some other secure data. What the Integer.toHexString() method does?

1) If the value of byte is between 0 and 15, Integer.toHexString() returns a String with 1 character among {0, 1, …, 9, a, b, c, d, e, f}.

2) If the value of byte is greater than 15, Integer.toHexString() returns a String with 2 characters.

Obviously, the first my idea to go round the problem is to append a leading zero to the StringBuffer object when Integer.toHexString() returns a String with 1 character.

Solution 1:


public static String getHexStringModified(byte[] array) {
    // save every byte in 2 characters.
    // Therefore hexString.length()=2*array.length
    StringBuffer hexString = new StringBuffer(2 * array.length);
    for (int i = 0; i < array.length; i++) {
       // From Integer's class API: This value is converted to a string
       // of ASCII digits in hexadecimal (base 16) with no extra leading 0s.
       String intBase16AsString = Integer.toHexString(OFFSET & array[i]);
       if (intBase16AsString.length() == 1) {
           hexString.append("0");
       }
       hexString.append(intBase16AsString);
    }
    return hexString.toString();
 }

After that I remembered that the previous code could be reduced if I use the class Formatter. Here is the refined code.

Solution 2:


public static String getHexStringModifiedAndRefined(byte[] array) {
   Formatter formatter = new Formatter();
   for (byte b : array) {
     formatter.format("%02x", b);
   }
   return formatter.toString();
 }

After that my colleague said me that there is better sollution and he mentioned me about some smart Apache’s library. So I found The Apache Commons project and more precisely the class Hex. Here it is the shortest solution (only on 1 row and the whole work is hidden in the Apache’s Hex class :))

Solution 3:


import org.apache.commons.codec.binary.Hex;
// ...
class HexStringTest {
   public static String getHexStringUltra(byte[] array) {
     for (int i = 0; i < array.length; i++) {
        array[i]=(byte)(OFFSET & array[i]);
     }
     return String.valueOf(Hex.encodeHex(array));
   }
}

Of course, there are also others solutions but this is easy and meet my needs.

Djingibi :)

Advertisements

About tsvetanv

Friends, Books, Music, Math, Programming.
This entry was posted in Java. Bookmark the permalink.

One Response to Java – convert a byte to a string representation of a integer as an unsigned integer in base 16

  1. shadrik says:

    Neat :)
    In the first code samples maybe it’ll be better to use StringBuilder, although it’s fine ine in that way as well :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s