summaryrefslogblamecommitdiffstats
path: root/src/lib.c
blob: 891fd271e8ce3c043177d653f707a416419703d7 (plain) (tree)






































                                                                                                 
/**
 * writes a hexadecimal representation of a binary string. does not NULL terminate destination.
 *
 * h and b may not overlap. period.
 * 
 * @param h	[out]	destination (requires 2l space)
 * @param b	[in]	source
 * @param l	[in]	length of source
 */

void bin2hex (char * h, const unsigned char * b, size_t l) {
	for (size_t i = 0; i < l; i++) {
		int ms = b[i] >> 4;
		int ls = b[i] & 0xF;
		assert(ms < 16);
		assert(ls < 16);
		*h++ = ms < 10 ? '0'+ms : 'a'+ms-10;
		*h++ = ls < 10 ? '0'+ls : 'a'+ls-10;
	}
}

/**
 * converts a hexadecimal string to bytes
 *
 * b and h may not overlap, unless they are the same address
 *
 * @param b	[out]	array of bytes to write to with capacity l
 * @param h	[in]	array of hex to read from with 2l hex digits
 * @param l	[in]	length of output array
 */

void hex2bin (unsigned char * b, const char * h, int l) {
	for (int i = 0; i < l; i++) {
		char ms = *h++;
		char ls = *h++;
		b[i] = (ms >= 'a' ? ms - 'a' + 10 : (ms >= 'A' ? ms - 'A' + 10 : ms - '0')) << 4;
		b[i] |= (ls >= 'a' ? ls - 'a' + 10 : (ls >= 'A' ? ls - 'A' + 10 : ls - '0'));
	}
}