ASCII To Binary

This algorithm converts ASCII code to binary numbers.



									/*****Please include following header files*****/
// stdint.h
/***********************************************/

char* CharToString(char c) {
	char* str = malloc(2);
	str[0] = c;
	str[1] = '\0';

	return str;
}

char* AppendString(const char* str1, const char* str2) {
	int str1Len = strlen(str1);
	int str2Len = strlen(str2);
	int strLen = str1Len + str2Len + 1;
	char* str = malloc(strLen);

	for (int i = 0; i < str1Len; i++)
		str[i] = str1[i];

	for (int i = 0; i < str2Len; i++)
		str[(str1Len + i)] = str2[i];

	str[strLen - 1] = '\0';

	return str;
}

char* GetSubString(char* str, int index, int count) {
	int strLen = strlen(str);
	int lastIndex = index + count;

	if (index >= 0 && lastIndex > strLen) return "";

	char* subStr = malloc(count + 1);

	for (int i = 0; i < count; i++) {
		subStr[i] = str[index + i];
	}

	subStr[count] = '\0';

	return subStr;
}

char* InsertString(char* str, int index, char* subStr) {
	char* s = GetSubString(str, 0, index);
	s = AppendString(s, subStr);
	s = AppendString(s, GetSubString(str, index, strlen(str) - index));

	return s;
}

char* DecimalToBinary(int dec)
{
	if (dec < 1) return "0";

	char* binStr = "";

	while (dec > 0)
	{
		binStr = InsertString(binStr, 0, CharToString((char)((dec % 2) + 48)));

		dec /= 2;
	}

	return binStr;
}

char* ASCIIToBinary(char* str) {
	char* bin = "";
	int strLength = strlen(str);

	for (int i = 0; i < strLength; ++i)
	{
		char* cBin = DecimalToBinary(str[i]);
		int cBinLength = strlen(cBin);

		if (cBinLength < 8) {
			for (size_t i = 0; i < (8 - cBinLength); i++)
				cBin = InsertString(cBin, 0, "0");
		}

		bin = AppendString(bin, cBin);
	}

	return bin;
}
								


Example

									char* data = "Programming Algorithms";
char* value = ASCIIToBinary(data);
								


Output

									01010000011100100110111101100111011100100110000101101101011011010110100101101110011001110010000001000001011011000110011101101111011100100110100101110100011010000110110101110011