dectobin

This is a discussion on dectobin within the C++ Programming forums, part of the General Programming Boards category; I was looking at the other things on this site and noticed the challenges. The dectobin problem looked easy so ...

  1. #1
    Rog
    Rog is offline
    Registered User
    Join Date
    Jan 2003
    Posts
    78

    dectobin

    I was looking at the other things on this site and noticed the challenges. The dectobin problem looked easy so I jumped on it... it took me no more than two minutes to get the basic algorithm working. Then I spent a few more minutes tweaking in the output formatting.

    I didn't look at the solution yet, but I am sure it is very similar to what I have...

    Well, here's my solution (for those who have an interest):

    Code:
    #include <iostream>
    
    int main(int argc, char* argv[])
    {
        if (2>argc) {
            std::cout << "usage: dectobin number\nwhere: number is a 32 bit decimal in the range 0 - 4294967295" << std::endl;
            return 1;
        }
    
        int num = 0;
        num = atoi(argv[1]);
    
        for (int i=31; i >=0; --i) {
            if (num>>i &0xffffffff) {
                if (num>>i &0x01)
                    std::cout << 1;
                else
                    std::cout << 0;
    
                if (i % 4 == 0)
                    std::cout << " ";
            }
        }
        return 0;
    }
    (note: I have only tested this on MSVS.NET 2003)

    I suppose I should go do the others now... though some of them look a bit more time consuming than this one

    Rog

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,801
    Use of a bitset makes problems like this a snap.

    [edit]
    Code:
    #include <iostream>
    #incldue <bitset>
    #include <cstdlib>
    
    int main(int argc, char* argv[])
    {
        if (argc != 2)
        {
            std::cout << "usage: dectobin number\nwhere: number is a 32 bit decimal in the range 0 - 4294967295" << std::endl;
            return 1;
        }
    
        std::cout << std::bitset<32>(atoi(argv[1])) << std::endl;
    
        return 0;
    }
    [/edit]
    Last edited by hk_mp5kpdw; 03-02-2005 at 05:47 AM.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Rog
    Rog is offline
    Registered User
    Join Date
    Jan 2003
    Posts
    78
    Quote Originally Posted by hk_mp5kpdw
    Code:
    std::cout << std::bitset<32>(atoi(argv[1])) << std::endl;
    COOL!

    But it isn't formatted and justified like mine is... I mean, mine is definitely easier to read. How would you filter the output from bitset to formate it like mine? (no leading zeros and broken into 4 bit sections, and please, no "exercise for the reader" cop outs )
    Last edited by Rog; 03-02-2005 at 08:07 AM.

  4. #4
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,801
    Adding formatting and dealing with leading zeros does require a bit more work. Having such requirements may make a bitset less attractive as a solution.

    Code:
    #include <iostream>
    #incldue <bitset>
    #include <cstdlib>
    #include <string>
    
    int main(int argc, char* argv[])
    {
        if (argc != 2)
        {
            std::cout << "usage: dectobin number\nwhere: number is a 32 bit decimal "
                         "in the range 0 - 4294967295" << std::endl;
            return 1;
        }
    
        // Save bitset as a string
        std::string str = std::bitset<32>(atoi(argv[1])).to_string();
    
        // Deal with / remove leading zeroes
        str = str.substr(str.find_first_of('1'));
    
        // Add space every 4th character starting from the end
        for( std::string::size_type indx = str.length()-4; indx > 0; indx -= 4 )
            str.insert(indx," ");
    
        // Output formatted string to console
        std::cout << str << std::endl;
    
        return 0;
    }
    Last edited by hk_mp5kpdw; 03-02-2005 at 09:42 AM. Reason: Replaced int indx with std::string::size_type indx
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  5. #5
    Rog
    Rog is offline
    Registered User
    Join Date
    Jan 2003
    Posts
    78
    Interesting. I like the way you utilize the standard library. The insert could represent undesired overhead (not in this little exercise, of course) , but that would depend on how the class was implemented. My hunch is that most mainstream string class implementations are more than adequate for all but the most stringent requirements.

    Thanks! that's good stuff,
    Rog

  6. #6
    Registered User
    Join Date
    Jun 2010
    Posts
    2

    Smile Re:dectobin

    Actually I donít think that my source code is best. It may have some problems. But Iíve come up with a different one than the given solution. Iím not using recursion like in the given one. Hence performance is high. So here is my code.

    Code:
    #include <iostream>
    #include <stdlib.h>
    using std::cout;
    using std::cerr;
    using std::endl;
    
    void		ConvertToBinary(int);
    
    int main(int argc, char* argv[])
    {
    	if (argc != 2)
    	{
    		cerr << "Incorrect execution\nUsage : <binary> <decimal value>\n";
    		return 1;
    	}
    
    	int		decimalNo = atoi(argv[1]);
    
    	ConvertToBinary(decimalNo);
    
    	return 0;
    }
    
    
    void ConvertToBinary(int decimalNo)
    {
    	cout << decimalNo << " in binary format is : ";
    	
    	int		binPlace = 1;
    	int		binCount = 0;	// no of bits needed
    	int		spaceIndex = 0;
    	int		leadingZeroes = 0;
    
    	// get the no of bits needed and maximum bit value
    	while (decimalNo >= binPlace)
    	{
    		binPlace *= 2;
    		binCount++;
    	}
    
    	if ( decimalNo != binPlace)
    	{
    		binPlace = binPlace / 2;
    	}
    
    	spaceIndex = binCount - 4;
    	leadingZeroes = 4 - ( binCount % 4 );
    
    	// print leading zeroes
    	for (int i = 0; i < leadingZeroes; i++)
    	{
    		cout << 0;
    	}
    
    	// print binary value
    	for (int i = 0; i < binCount; i++)
    	{
    		// print space after each 4 bit
    		if ( i  == spaceIndex )
    		{
    			cout << " ";
    			spaceIndex -= 4;
    		}
    
    		if ( decimalNo >= binPlace )
    		{
    			cout << 1;
    			decimalNo -= binPlace;
    		}
    		else
    		{
    			cout << 0;
    		}
    
    		binPlace /= 2;
    	}	
    	cout << endl;
    }

  7. #7
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,801
    Don't bump 5+ year old posts.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21