/*
 * The Initial Developer of the Original Code is International
 * Business Machines Corporation. Portions created by IBM
 * Corporation are Copyright (C) 2007 International Business
 * Machines Corporation. All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the Common Public License as published by
 * IBM Corporation; either version 1 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * Common Public License for more details.
 *
 * You should have received a copy of the Common Public License
 * along with this program; if not, a copy can be viewed at
 * http://www.opensource.org/licenses/cpl1.0.php.
 */

#include <stdio.h>
#include <stdlib.h>

int hex2bin(void *dest, const void *src, size_t n)
{
	int i, j;
	unsigned char *usdest = (unsigned char *) dest;
	unsigned char *ussrc = (unsigned char *) src;

	if (n & 0x01) {
		printf("ERROR: hex2bin wrong size %d\n", n);
		return -1;
	}

	for (i = 0; i < n / 2; i++) {
		j = i * 2;
		usdest[i] = 0;
		if ((0x30 <= ussrc[j]) && (ussrc[j] <= 0x39)) {
			usdest[i] = (ussrc[j] - 0x30) << 4;
		}
		if ((0x41 <= ussrc[j]) && (ussrc[j] <= 0x46)) {
			usdest[i] = (ussrc[j] - 56) << 4;
		}
		if ((0x61 <= ussrc[j]) && (ussrc[j] <= 0x66)) {
			usdest[i] = (ussrc[j] - 87) << 4;
		}

		if ((0x30 <= ussrc[j + 1]) && (ussrc[j + 1] <= 0x39)) {
			usdest[i] |= ussrc[j + 1] - 0x30;
		}
		if ((0x41 <= ussrc[j + 1]) && (ussrc[j + 1] <= 0x46)) {
			usdest[i] |= ussrc[j + 1] - 56;
		}
		if ((0x61 <= ussrc[j + 1]) && (ussrc[j + 1] <= 0x66)) {
			usdest[i] |= ussrc[j + 1] - 87;
		}
	}

	return i;
}

void printhex(char *str, unsigned char *buf, int len)
{
	int i;
	printf("%s", str);
	for (i = 0; i < len; i++)
		printf("%02x", buf[i]);
	printf("\n");
}

void fprinthex(FILE * fp, char *str, unsigned char *buf, int len)
{
	int i;
	fprintf(fp, "%s", str);
	for (i = 0; i < len; i++)
		fprintf(fp, "%02x", buf[i]);
	fprintf(fp, "\n");
}

void fprinthex2(FILE * fp, char *str, unsigned char *buf, int len)
{
	int i;
	for (i = 0; i < len; i++) {
		fprintf(fp, "%s", str);
		fprintf(fp, "%02X", buf[i]);
	}
	fprintf(fp, "\n");
}
