#include <stdio.h>
#include <math.h>
/* converts to binary using logs */
int main()
{
long int decimalNUM = 0, binaryNUM = 0, exponentNUM = 0;
printf("Enter a number to be converted to binary.\t");
scanf("%ld", &decimalNUM);
fflush(stdin);
int origDEC = decimalNUM;
while (decimalNUM > 0)
{
exponentNUM = (log(decimalNUM))/(log(2));
binaryNUM += pow(10, exponentNUM);
decimalNUM -= pow(2, exponentNUM);
}
printf("\nBINARY FORM OF %ld is %ld", origDEC, binaryNUM);
getchar();
return binaryNUM;
}
If STDIN is 4 it returns 99 and it should not. On IDEONE it returns 100. Why?
EDIT seems that any even number above two returns something with nines in it
Floating point operations like log are not exact. On my machine this code runs as expected (4 on STDIN gives 100).
One way you could do this, is by using the mod (%) operator with successive powers of two.