/* john pfeiffer 15jan06 converts a positive decimal number to up to an 8 digit binary number
2^0 = 1, 2^1 = 2, 2^2 = 4, 2^3 = 8, 2^4 =16, 2^5 =32
case 0=0, case 1=0, case 2=1, case 3=1, case 4 = 2
fixed/updated jan09
*/
#include <stdio.h>
#include <stdlib.h>
/* stdlib for abs */
/* pow returns float (for neg values!), exponent function handles positive exp, exp=0, and even negative exp.
*/
float pow(int base, int exponent)
{
int i=1;
float result=1;
int negexp = 0;
if( exponent !=0 ) /* special case, exp = 0, just return 1 */
{ if( exponent < 0 ) /* negative exponent */
{ negexp = 1;
exponent = abs(exponent);
}
for(i=1; i < exponent+1; i++)
{ result = result * ((float)base); }
}
if( negexp == 1 ) /* negative exponents create small numbers */
{ result = (1 / result); }
return result;
}/* end func pow */
int main(int argc, char* argv[])
{
int decimal = 35;
int i=0;
int k=0;
int binary_digits[8]; /* up to 8 binary digits? */
for(k=0; k<8; k++)
{ binary_digits[k] = 0; }
printf("decimal: %d\n",decimal); /* print before we transform dec */
if( decimal != 0) /* if dec == 0 then we can just print our default 0's */
{ do
{ i=1;
if( decimal == 1 ) /* special case of 2^0 = 1 */
{ binary_digits[i] = 1; }
else
{ while( pow(2,i) <= ((float)decimal) ) /* pow returns float */
{ i++; }
binary_digits[i-1] = 1;
}
decimal = decimal - ((int)pow(2,i-1));
}while( decimal > 0 );
}
printf("binary: ");
for(k=7; k>=0; k--)
{ printf("%d", binary_digits[k]); }
printf("\n");
printf("\nexample of pow function and negative exponents\n");
printf("\n%d^%d=%f\n",3,5,pow(3,5));
printf("\n%d^%d=%f\n",3,-2,pow(3,-2));
return 0;
}/* end main */