Java: Bytes, Hex and Serialization

Posted on

This is again another short Java development post. Here I show some convenient functions for use with byte arrays in Java.

Byte Array to Hex String

Converting byte arrays into a textual format comes in handy in many scenarios. For one instance when you need to store a cryptographic key on disk in a textual format you can choose to encode into Base64 (which will increase the size by 33%) or convert each byte to a textual hex representation. I personally found this handy when dealing with the Apache Derby embedded database, I had to feed it the cryptographic key as a hex string. Other uses I found was for debugging and when comparing objects together. Below is the function that takes a byte array as a parameter and returns its representation as a Hex String.

private static final char[] HEX_CHARS = {
	'0', '1', '2' ,'3', '4', '5', '6', '7', '8', '9',
	'a', 'b', 'c', 'd', 'e', 'f'
};

public String toHexString(byte[] bytes)
{
	StringBuilder sb = new StringBuilder();
	for(int i = 0; i < bytes.length; i++) {
		byte b = bytes[i];
		sb.append(new char[] {HEX_CHARS[(b >> 4) & 0x0f], HEX_CHARS[b & 0x0f]});
	}
	
	return sb.toString();
}

Object Serialization To and From Bytes

This has always been a common milestone for many developers when they start developing some serious applications. We tend to use Objects a lot due to the OO nature of Java (which is not a bad thing), so we need to be able to send these objects off as bytes to somewhere (I/O Streams, disk …etc) Below is the standard implementation of serializing and deserializing objects to bytes and back again.

public byte[] serializeObject(Object obj) throws IOException
{
	ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
	ObjectOutputStream oos = new ObjectOutputStream(bytesOut);
    	oos.writeObject(obj);
    	oos.flush();
    	byte[] bytes = bytesOut.toByteArray();
    	bytesOut.close();
    	oos.close();
    	return bytes;
}


public Object deserializeBytes(byte[] bytes) throws IOException, ClassNotFoundException
{
	ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytes);
    	ObjectInputStream ois = new ObjectInputStream(bytesIn);
    	Object obj = ois.readObject();
	bytesIn.close();
    	ois.close();
    	return obj;
}
Advertisements

Leave a Comment

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