/**
 * File:    ByteStringConv.java
 * Created: 30.03.2006
 *
/*******************************************************************************
 * Copyright (c) 2005-2011
 * University of Augsburg, Germany <www.ds-lab.org>
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Markus Bauer, Programming distributed Systems Lab, University of Augsburg 
 *    	- initial API and implementation
 *******************************************************************************/


package org.eclipse.jwt.we.misc.util.internal;

import java.math.BigInteger;

/**
 * 
 * Tools to switch between String a byte[]
 * 
 */
public class ByteStringConv
{

	/**
	 * Creates a string out of an byte array. If the byte array contains the numbers 0xff,
	 * 0xea, the string will look like ffea.
	 * 
	 * @param array
	 *            the byte array that has to be converted
	 * @return string
	 */
	public static String createString(byte[] array)
	{
		StringBuffer sb = new StringBuffer(array.length * 2);// StringBuilder in 1.5
		for (int x = 0; x < array.length; x++)
		{
			String str = Integer.toHexString(0xff & array[x]);
			if (str.length() == 1)
				str = "0" + str; //$NON-NLS-1$
			sb.append(str);
		}
		return sb.toString();
	}


	/**
	 * Creates a byte array out of a string that has been created with createString above.
	 * 
	 * @param str
	 *            The string to be converted
	 * @return byte array
	 */
	public static byte[] createByteArray(String str)
	{
		byte[] array = new BigInteger(str, 16).toByteArray();
		if (array.length > 0)
		{
			byte[] newarr = new byte[array.length - 1];
			for (int i = 0; i < newarr.length; i++)
			{
				newarr[i] = array[i + 1];
			}
			array = newarr;
		}
		return array;
	}
}
