nifty little thing i made

This is a discussion on nifty little thing i made within the C++ Programming forums, part of the General Programming Boards category; Here is a nifty little thing I made. All of us have probably made a base 10 to base 2 ...

  1. #1
    l'Anziano DavidP's Avatar
    Join Date
    Aug 2001
    Location
    Plano, Texas, United States
    Posts
    2,738

    Cool nifty little thing i made

    Here is a nifty little thing I made.

    All of us have probably made a base 10 to base 2 converter before. Well, I took a new approach to it.

    The most common approach is to mod by 2 recursively until you finally get down to 1's and 0's and form a base 2 number.

    I did it quite differently.

    I originally did this using ANSI C (char pointers, etc.), and it will definitely work that way if you want to make a version like that, but I changed it to use the STL string class to make it more readable.

    Code:
    #include <string>
    
    #define BIT_1_MASK 0x00000001
    
    string ConvertToBaseTwo ( int k )
    {
    	string binary;
       char *c = new char;
    
       for ( int i = 0; i < (sizeof(int)*8); i++ )
       {
    		*c = ((k >> i) & BIT_1_MASK) + '0';
       	binary.prepend( c, 0, 1 );
       }
    
       binary.remove ( 0, binary.find_first_of("1"));
    
       return binary;
    }
    My Website

    "Circular logic is good because it is."

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,786
    You may also wish to try

    Code:
    template<typename T>
    std::string ConvertToBaseTwo(T k)
    {
    	std::stringstream ss;
    	ss << std::bitset<std::numeric_limits<T>::digits>(k);
    	return ss.str();
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 10-27-2006, 01:21 PM
  2. What was the first game you ever made?
    By jverkoey in forum Game Programming
    Replies: 0
    Last Post: 02-12-2003, 10:09 PM
  3. What's the best program you have ever made?
    By Kevin.j in forum A Brief History of Cprogramming.com
    Replies: 31
    Last Post: 10-02-2002, 11:29 AM
  4. Is there a bug in this part of my algorithm for connect 4?
    By Nutshell in forum Game Programming
    Replies: 8
    Last Post: 04-28-2002, 01:58 AM

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