Reading and writing HEX formatted data from and to ByteArray

These utility method might become handy sometimes.

package com.paazmaya.util
{
    import [flash.utils.ByteArray](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/ByteArray.html " The ByteArray class provides methods and properties to optimize reading, writing, and working with binary data. ");

    /**
     * Utility for reading and writing Hex formatted data to/from ByteArray.
     */
    public class Hex
    {
        /**
         * Write the given hex string to the bytearray
         *
         * @param   ba
         * @param   hex
         * @return  ByteArray that has the hex written in it
         */
        public static function writeBytes(ba:ByteArray, hex:String):ByteArray
        {
            ba.position = ba.length;
            var len:uint = hex.length;
            trace("writeBytes. len: " + len);
            for (var i:uint = 0; i < len; i += 2)
            {
                var byte:uint = uint("0x" + hex.substr(i, 2));
                ba.writeByte(byte);
            }
            return ba;
        }

        /**
         * Read the bytes of the given bytearray and convert to a hex string
         *
         * @param   ba
         * @return  String in hex format
         */
        public static function readBytes(ba:ByteArray):String
        {
            var hex:String = "";
            ba.position = 0;
            var len:uint = ba.length;
            trace("readBytes. len: " + len);
            for (var i:uint = 0; i < len; ++i)
            {
                var byte:uint = ba.readUnsignedByte();
                //trace("readBytes. byte " + i + ": " + byte + " -- " + byte.toString(16));
                hex += byte.toString(16).substr(-2);
            }
            return hex;
        }
    }
}

Example usage:

var helloText:String = "Hello there!";
var data:ByteArray = new ByteArray();
data.writeUTFBytes(helloText);
trace("helloText in HEX: " + Hex.readBytes(data)); // 48656c6c6f20746865726521
data.clear();
data = Hex.writeBytes(data, "48656c6c6f20746865726521");
data.position = 0;
trace("HEX to string: " + data.readUTFBytes(data.length)); // Hello there!

This class is also now in XIFF trunk, in order to help debugging Stream Compression feature.