Assignment:
Write a function zet_om_naar_getal(getal) that calculates the binary representation from a decimal number as a string, using recursion.

What I have so far:

string zet_om_naar_binair(double getal)
{
    string binair;

    if(getal >= 1)
    {
        binair += '0' + static_cast<int>(getal)%2;
        binair += zet_om_naar_binair(getal/2);
    }
    else if(getal > 0)
    {
        double dubbel = 2*getal;
        binair += '0' + static_cast<int>(dubbel)%2;
        binair += zet_om_naar_binair(dubbel - static_cast<int>(dubbel));
    }

    return binair;
}

Don't mind the weird names, they're in Dutch.

So far, it translates the number correctly in 2 parts, before the digit, and after. However, the part before the digit is reversed, so I'd have to flip it around, and add a '.'.
In the case where the number is smaller than 1, I'd have to add "0." in front...
I have no clue of how going about either of them.. I can't think of a good place to put it in because it's recursive.

Thanks for any ideas!

string dec2bin2(int intNum)
{	//2147483648 = INT_MAX
	string strRetVal = "";
	int intTemp = intNum;
	
	for(unsigned long ulngLoop = ((unsigned long)1+INT_MAX); ulngLoop > 0; (ulngLoop/=2))
	{
		if((unsigned)intTemp >= ulngLoop)
		{
			strRetVal += "1";
			intTemp -= ulngLoop;
		}
		else
		{
			strRetVal += "0";
		}
	}
	
	return strRetVal;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.