/*******************************************************************************
 * Copyright (c) 2007, 2008 IBM Corporation
 * 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:
 *     IBM Corporation - initial API and implementation
 ******************************************************************************/
package org.eclipse.cosmos.me.internal.deployment.sdd.tooling.btg.rpm.util;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;

public class HexUtils {
	public static byte[] hexToByte(String hex) {
		byte[] bytes = new byte[hex.length() / 2];

		for (int i = 0; i < bytes.length; i++) {
			bytes[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2),
					16);
		}

		return bytes;
	}

	public static String byteToHex(byte data) {
		StringBuffer buf = new StringBuffer();
		buf.append(toHexChar((data >>> 4) & 0x0F));
		buf.append(toHexChar(data & 0x0F));
		return buf.toString();
	}

	public static String bytesToHex(byte[] data) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < data.length; i++) {
			buf.append(byteToHex(data[i]));
		}
		return (buf.toString());
	}

	public static char toHexChar(int i) {
		if ((0 <= i) && (i <= 9))
			return (char) ('0' + i);
		else
			return (char) ('a' + (i - 10));
	}

	public static int bytesToInt(byte[] data) throws IOException {
		byte[] bytes = new byte[4];

		if (data.length > 4) {
			// TODO: throw exception
		} else if (data.length == 4) {
			bytes = data;
		} else if (data.length < 4) {
			for (int i = 0; i < 4 - data.length; i++) {
				bytes[i] = new Byte("00").byteValue();
			}

			for (int i = 0; i < data.length; i++) {
				bytes[i + (4 - data.length)] = data[i];
			}
		}

		ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
		DataInputStream in = new DataInputStream(bis);

		return in.readInt();
	}
}
