So here is my code
void ascToBinary(int character, int *ones)
{
if(character == 1)
{
printf("1");
*ones+=1;
return;
}
else
{
if((character%2) == 0)
{
printf("0");
character = character/2;
}
else
{
printf("1");
character = character/2;
*ones+=1;
}
binaryPrinter(character, ones);
}
}
Can anyone try to help me out on where something is wrong here. It compiles fine and does some ascii letters correct. If you try an 'e' though it will print out '1010011' instead of the correct binary.
All help appreciated Thanks Guys.
You print the results in the wrong order. The correct output is '1100101'. You can flip it like this:
void ascToBinary(int character, int *ones)
{
if(character == 1)
{
printf("1");
*ones+=1;
return;
}
else
{
char out;
if((character%2) == 0)
{
out = '0';
character = character/2;
}
else
{
out = '1';
character = character/2;
*ones+=1;
}
ascToBinary(character, ones);
putchar (out);
}
}
You're printing the bits of the character in reverse, since you start printing with the least significant bit.
Therefore the expected value for your function, when called on e
is 1010011
which is exactly what you get.
Converting an Integer to binary:
Version 1 - Will print out the binary result
void to_bin(int value)
{
char base_range[] = "01";
if (value >= 2) {
to_bin(value / 2);
}
printf("%c", base_range[value % 2]);
}
Version 2 - Will return a string with binary result
void to_bin_str(int value, char *res, int *p)
{
char base_range[] = "01";
if (value >= 2) {
to_bin_str(value / 2, res, p);
}
res[(*p)++] = base_range[value % 2];
}
char* convert(int value)
{
char* result = (char*)malloc(sizeof(char) * 32);
int i = 0;
to_bin_str(value, result, &i);
result[i] = '\0';
return (result);
}
Version 3 - Will convert to any base from 2 to 16, handles negatives for base 10
void to_base(int value, int base, char *res, int *p)
{
char base_range[] = "0123456789ABCDEF";
if (value >= base || value <= -base) {
to_base(value / base, base, res, p);
}
res[(*p)++] = base_range[abs(value % base)];
}
char* convert(int value, int base)
{
char *result = (char*)malloc(sizeof(char) * 32);
int i = 0;
if (base < 2 || base > 16)
return (NULL);
if (base == 10 && value < 0)
result[i++] = '-';
to_base(value, base, result, &i);
result[i] = '\0';
return (result);
}