java bytes and strings

I’m posting this code snippet here because a) it took me a while to figure it out and b) I couldn’t find anything like it out on the big bad internet.

Problem: convert a 24-byte hex array (unsigned bytes) to a string, and back again. A byte can range from values 0 to 255, or 0x00 to 0xff. Seems simple, except Java treats its native ‘byte’ type as a signed integer, which means values range from -128 to 128. So 0xFD as a signed byte is ‘-3’, while it is ‘253’ as unsigned. And… each byte must be represented by two digits.


Convert a byte array to a string:

private String convertByteArrayToHexString(byte[] buf) {
        StringBuffer sbuff = new StringBuffer();
        for (int i=0; i<buf .length; i++) {
            int b = buf[i];
            if (b < 0) b = b & 0xFF;
            if (b<16) sbuff.append("0");
        return sbuff.toString();

And back to a byte array again:

private  byte[] convertHexStringtoByteArray(String hex) {
        java.util.Vector res = new java.util.Vector();
        String part;
        int pos = 0; //position in hex string
        final int len = 2; //always get 2 items.
        while (pos < hex.length()) {
            part = hex.substring(pos,pos+len);
            pos += len;
            int byteVal = Integer.parseInt(part,16);
            res.add(new Byte((byte)byteVal));
        if (res.size() > 0) {
            byte[] b = new byte[res.size()];
            for (int i=0; i<res .size(); i++) {
                Byte a = (Byte)res.elementAt(i);
                b[i] = a.byteValue();
            return b;
        } else {
            return null;

There ya have it.

Comments are closed.