/*(c) 2006 - 2008 AllenPort Co. All Rights Reserved.
All versions of this code, including the source and executable versions, 
constitute the intellectual property of AllenPort Co., which expressly reserves 
any and all U.S. and foreign rights and benefits to the code under copyright, 
trade secret and any other intellectual property law or international treaty 
whatsoever. Use of the code is subject to the terms and conditions of a separate 
written license agreement, and the code shall not be reproduced, modified, distributed 
or otherwise used in any form or manner whatsoever without obtaining the prior written 
permission of AllenPort Co. Any unauthorized reproduction or distribution of the code, 
or any portion of it, may result in civil and criminal penalties and be prosecuted 
to the fullest extent of the law.*/
// This function takes an array of bytes (byteArray) and converts them
// to a hexadecimal string. Array element 0 is found at the beginning of 
// the resulting string, high nibble first. Consecutive elements follow
// similarly, for example [16, 255] --> "10ff". The function returns a 
// string.

function byteArrayToHex(byteArray) {
  var result = "";
  if (!byteArray)
    return;
  for (var i=0; i<byteArray.length; i++)
    result += ((byteArray[i]<16) ? "0" : "") + byteArray[i].toString(16);

  return result;
}

// This function converts a string containing hexadecimal digits to an 
// array of bytes. The resulting byte array is filled in the order the
// values occur in the string, for example "10FF" --> [16, 255]. This
// function returns an array. 

function hexToByteArray(hexString) {
  var byteArray = [];
  if (hexString.length % 2)             // must have even length
    return;
  if (hexString.indexOf("0x") == 0 || hexString.indexOf("0X") == 0)
    hexString = hexString.substring(2);
  for (var i = 0; i<hexString.length; i += 2) 
    byteArray[Math.floor(i/2)] = parseInt(hexString.slice(i, i+2), 16);
  return byteArray;
}

function byteArrayToString(dataArray)
{
  var res = '';
	for(var i = 0; i < dataArray.length; ++i)
		res += String.fromCharCode(dataArray[i]);
	return res;
}

function stringToByteArray(dataString)
{
  var res = [];
	for(var i = 0; i < dataString.length; ++i)
		res[i] = dataString.charCodeAt(i);
	return res;
}

function hexToString(hexString)
{
  return byteArrayToString(hexToByteArray(hexString));
}

function stringToHex(dataString)
{
  return byteArrayToHex(stringToByteArray(dataString));
}

