Integer/Character converter to binary
I wrote this code purely for educational purposes. It also helped
learn more about how exactly things look in memory, so it helped me in that aspect. I'm posting this in order to obtain any suggestions you may have on the code I have right now ( I will likely add more and change it in the future)
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#define LINE "\n--------------------------------------------------------------------------------\n"
char * int2bin(int number);
void DrawLine();
int main()
{
char ans = ' ';
char cinput = ' ';
int input = 0;
char * memoryallocated;
DrawLine();
printf(" Do you want to translate integers or \ncharacters to binary? [i/c]\n\n");
scanf("%1c", &ans);
DrawLine();
if (toupper(ans) == 'I') {
printf("Type in a number and press enter to convert a number to binary! \n");
DrawLine();
do
{
fflush(stdin);
scanf("%d", &input );
DrawLine();
memoryallocated = int2bin(input);
DrawLine();
if (memoryallocated != NULL) { free(memoryallocated); } else {exit(1); break;}
} while (1);
} else if (toupper(ans) == 'C') {
printf("Type in a character and press enter to convert it to binary! \n");
DrawLine();
do {
fflush(stdin);
scanf("%1c", &cinput );
DrawLine();
memoryallocated = int2bin((int)cinput);
DrawLine();
if (memoryallocated != NULL) { free(memoryallocated); } else {exit(1); break;}
} while(1);
}
return 1;
}
char * int2bin(int number)
{
char * StartOfBin;
char * BinPtr;
size_t MemAmount;
int bitnum = 4;
int charbyteamount = 1;
int PlaceValue;
int n = 0;
int ctr = 0;
int * tempmem = (int *)malloc(1 * sizeof(int));
*(tempmem + 0) = number;
do
{
if (number <= (pow(2, bitnum) - 1)) {StartOfBin = (char*)malloc(MemAmount = (sizeof(char)* ((4 * charbyteamount) + 1))); break; }
bitnum *= 2;
charbyteamount *= 2;
} while (1);
BinPtr = StartOfBin;
if ( StartOfBin != NULL ) {
for(; n < (MemAmount - 1); n++) { *(BinPtr + n) = '0'; }
*(BinPtr + (n)) = '\0';
} else return NULL;
BinPtr = StartOfBin;
PlaceValue = (pow(2,n)/2);
do
{
if (number >= PlaceValue) {
*(BinPtr + 0) = 0b00110001; // '1'
number -= PlaceValue;
PlaceValue /= 2;
BinPtr++;
ctr++;
} else {
PlaceValue /= 2;
BinPtr++;
ctr++;
}
} while (ctr < n);
printf("%d = %s \n", *(tempmem+0), StartOfBin);
free(tempmem);
return StartOfBin;
}
void DrawLine() { printf("%s", LINE); }