A Guide to Mobile and Web Technology(LAMP)

The following code block helps you to convert a byte array to hex string format.

private String byteArrayToHexString(byte in[]){
        byte ch = 0x00;
        int i = 0;
        if (in == null || in.length <= 0){
            return null;
        }
        String pseudo[] = {"0", "1", "2","3", "4", "5", "6", "7", "8","9", "A", "B", "C", "D", "E", "F"};
        StringBuffer out_str_buf = new StringBuffer(in.length * 2);
        while (i < in.length){
            ch = (byte) (in[i] & 0xF0); // Strip off high nibble
            ch = (byte) (ch >>> 4);     // shift the bits down
            ch = (byte) (ch & 0x0F);    // must do this is high order bit is on!
            out_str_buf.append(pseudo[ (int) ch]); // convert the nibble to a String Character
            ch = (byte) (in[i] & 0x0F); // Strip off low nibble
            out_str_buf.append(pseudo[ (int) ch]); // convert the nibble to a String Character
            i++;
        }
        String rslt = new String(out_str_buf);
        return rslt;
    }
Advertisements

Comments on: "How to convert a Byte Array to Hex String" (1)

  1. This is one I wrote in scala.

    def binary2String(value: Array[Int]): String = {
    value.length match {
    case 1 if (value(0) == 0) => “”
    case _ => value.map(_.asInstanceOf[Char]).mkString
    }
    }

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

%d bloggers like this: