Hi Guys
Ive searched the forum but havent found much on decimal to binary so i came up with my own algorithm. However im encountering a seg fault and dont know where the problem lies.
My algorithm to convert decimal to binary is:
get the number
find the highest power of 2
compare the number with highest power
if number greater the highest power print a 1
adjust the new number
adjust the new power
end when there is a zero.
Cheers
Code:
void dec2bin( void ) {
{
int num;
int highestpower=1;
int i;
printf( "Enter a decimal number: " );
scanf( "%d", &num );
for ( i=1; i<=num; i++ ) {
if ( highestpower <= num )
highestpower = intpow( 2, i );
else if ( highestpower > num )
break;
}
while ( num != 0 ) {
if ( num >= highestpower ) {
putchar( '1' );
num = num - highestpower;
highestpower = highestpower - intpow( 2, sqrt(highestpower)-1);
}
else {
putchar( '0' );
highestpower = highestpower - intpow( 2, sqrt(highestpower)-1);
}
}
}
int intpow( int base, int power )
{
if ( power == 0 )
return 1;
else
return base * intpow( base, power-1 );
}