Click here to Skip to main content
15,896,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Wrote a program to convert a number to binary in C++ .I'm fairly new to C++ and I did this before and it wasn't done too well, but I feel like I made a few improvements. Please if there are any bad practices or something I might have done wrong, let me know. I know my naming isn't too well but i don't put much thought into that. Thanks.

C++
#include <iostream>
#include <vector>
#include <string>
#include <iterator>
#include <fstream>
#include "modeset.h"
#include <locale>
#include <sstream>


using std::cout;
using std::cin;
using std::vector;
using std::string;
using std::endl;
using std::cerr;
using std::stringstream;


int convert_to_bin(int user_conv_num)
{
    stringstream bin_in_string;//stringstream to store int result in

    if(user_conv_num == 0)
    {

        return 0;

    }


     convert_to_bin(user_conv_num / 2);//We call convert_to_bin function while dividing user_conv_num in the parameter because the modulus operator does not divide for us


     bin_in_string<<user_conv_num % 2;//Get the reminder using the modulus operator, this does not divide user_conv_num by two, it only gets the remainder and writes it to bin_in_string


     cout<<bin_in_string.str();//print result

     return 0;
}

int main()
{
    long int user_conv_num = 0;


cout<<"(#)";

cin>>user_conv_num;


    try
    {


      if(user_conv_num < 0) //if negative number
        throw 1; //throw int exception


      else
        {

        convert_to_bin(user_conv_num); //if not a negative number , do the conversion

        }

    }

    catch (int) //catch int exception if true
    {

        cerr<<"Negative integer";

    }

}
Posted

You approach is inefficient and more complex than it has to be. I'll just give you the right idea:

You need to test all bits in the integer value and write 0 is the bit is set, 1 is the bit is not set. How to do it? First create an integer with N-th bit set. Let's call this number a "mask" (this is what it is, its purpose). This is done by the left shift of 1 using the shift operator '<<': If the bit's number is N, the mask is 1 << N.

After that, calculate binary AND of the integer value you test and the mask, using the bitwise '&' operator. If the bit N is clear, the result or AND operation is zero, non-zero otherwise.

This is all you need.

See also: http://www.learncpp.com/cpp-tutorial/38-bitwise-operators[^].

[EDIT]

Also, there is no a need to check up for negative integer. You can represent negative integers in exact same way as positive; the algorithm is totally agnostic to the sign. By the way, the integers are usually represented using two's complement representation, which makes the arithmetic operations agnostic to the sign. This is an interesting and important matter, must-know for all software developers: http://en.wikipedia.org/wiki/Two%27s_complement[^].

—SA
 
Share this answer
 
v3
Comments
Stefan_Lang 27-Oct-14 7:33am    
I'd suggest not using the knowledge of the internal representation for treating negative numbers: the task as described only asks for the binary representation, not for an interpretation what is what.
Sergey Alexandrovich Kryukov 27-Oct-14 8:18am    
I am not suggesting doing it. I only say this is important knowledge.

Pay attention for the context: this is the situation when bits are shown, which, in particular, gives the information on the internal representation. This is just given. The real point is: in the algorithm I explained, it is shown correctly regardless of any particular representation and sign of the number.

As I say, this is given. If someone needs to see the bits, this is needed for something. There are many cases where bits control something. One example: hardware; say, one bits open/close some relay. And so on...

—SA
[no name] 27-Oct-14 19:04pm    
Sergey , you saw my previous code, is this at least better than my previous code?
Sergey Alexandrovich Kryukov 27-Oct-14 20:18pm    
Both are not good. You need to use left shifted 1 as a mask and bitwise '&', nothing else. What's unclear?
—SA
Stefan_Lang 28-Oct-14 4:15am    
I understand. But the question is whether the task is to show the internal representation - in which case we don't need to know what the internal format means - or whether we just want a conversion to base 2 - in which case we need to print the converted value of -2 as "-10", not "1111111111111101". Either way it is not necessary to know what internal representation is used.
This is the complete solution, with one of the possible options to output the result of conversion:
C++
void ToBinary(char* string, int number) {
    int length = 8 * sizeof number;
    for (int bit = 0; bit <= length; ++bit) {
        int mask = 1 << bit;
        if ((mask & number) == 0)
            string[length - bit] = '0';
        else
            string[length - bit] = '1';
    }
    string[length] = (char)0;
}
It's assumed that the parameter string should point to memory having enough room for all binary digits.

I'm disappointed.

—SA
 
Share this answer
 
v2
Comments
[no name] 30-Oct-14 18:36pm    
I do not know how long it takes for you to evaluate someone enough to be disappointed at them after 2 questions. I was not looking for a solution nor an opinion on my thinking. You managed to turn this question into a assumption driven topic left to be laughed at by all members. I understand you are a valuable member to this forums and I frequently see your name on the lists, but to degrade someone to the point were you assumed I was not thinking at all is my flag to know that this community is not for me . As for your solution, I will do absolutely nothing with it besides basic studying of what happens in it, further than that is a waste of my time. Just as a word of advice, take time setting standards and evaluating people before you feel "disappointed". To any members of the community that they felt I wasted any of their time, I send you my formal apologies. Good bye, thank you for at least taking the common courtesy and time to review my questions Sergey.
Sergey Alexandrovich Kryukov 30-Oct-14 21:09pm    
No, no, please don't take me wrong. I am not trying to generalize any opinion on your personally; of course I don't know about you.
Did I tell you what am I disappointed with? Only with your action on this very page nothing else. I expected you to do more by yourself. I did not mean to "evaluate" you at all.
At the same time, I cannot bend the truth: I really have been disappointed; and I'm still disappointed. Should I have lied that I wasn't? :-)

Sorry if it hurts you in any way. No, of course, you did not ask for the code; that was my act of giving up. (I already almost sorry about that post.) By the way, if you think that my mistake was wrong assumption on what you should know, tell me about that. Of course it could be my mistake. We all understand that some lack of knowledge is not a sin. But I would add that working at the problem, putting considerable effort is important.

—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900