Click here to Skip to main content
15,215,075 members
Rate this:
Please Sign up or sign in to vote.
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.

#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;




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


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



    catch (int) //catch int exception if true

        cerr<<"Negative integer";


Rate this:
Please Sign up or sign in to vote.

Solution 1

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:[^].


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:[^].

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.
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...

[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?
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.
[no name] 27-Oct-14 22:06pm
I read the tutorial for bit-wise operators, and what's unclear is everything after the headings for Bitwise AND, OR , XOR. I just want to put a number and convert it into binary, how did the author in the tutorial start of with the binary numbers, what is the basic format for bit-wise operators, if i want a vector i just write vector<int> SomeVector, but how do i even start with bitwise operators? Do i just write Z<<1 , and just shift everything one to the left? How does that convert anything to 0's and 1's, and if it does, WHY shift it? What if its the number 8 in binary which is 1000, and I shift it the left 1, it's just going to 0000. On top of all that, I DO understand how the NOT operator works and flips all the bits, aren't bits in intervals of 4? I understand i could be completely off-topic with this, but when it comes to shifting them to the left by 1, I just can't see how it will work. That being said, I do not expect you to spend much effort explaining it to a rookie, I will eventually understand it but right now i just do not see how this all works.
Sergey Alexandrovich Kryukov 27-Oct-14 22:53pm
You don't need anything beyond simple operations I described. What is unclear?
No, you don't write Z<<1, you write int mask = 1<<N, where N is the number of bit. In means "shift 1 to the left be N bits". So "1" moves to the position of N-th bit. And then you calculate (Z & mask), if Z is your number to test (convert).
[no name] 27-Oct-14 23:51pm
Ok explain this to me:

#include <iostream>
int main(){
int mask = 1<<N;
int number_to_convert;


int b = number_to_convert & mask

What do i do now with the N? I shift it N bits, by N-bits do you mean how many bits the type being converted is?
Sergey Alexandrovich Kryukov 28-Oct-14 10:42am
Could you put just a bit of thinking?
[no name] 29-Oct-14 19:41pm
I get it now
Sergey Alexandrovich Kryukov 29-Oct-14 19:45pm
Great. I'm really happy.
Will you now accept the answer formally (green "Accept" button)?
[no name] 29-Oct-14 19:52pm
I believe that requires some thinking.
Sergey Alexandrovich Kryukov 29-Oct-14 20:06pm
That is what I suggested in first place... :-)
[no name] 29-Oct-14 20:24pm
Am I at least on the right track , i get the idea but not too sure how to write it.

#include <iostream>
using namespace std;

int main()
int x = 0;
int mask = 1<<sizeof(x);

Sergey Alexandrovich Kryukov 29-Oct-14 20:40pm
This is complete gibberish. I'm almost ready to advise you to give and do something else....
[no name] 29-Oct-14 20:54pm
Maybe after I go past the level of a rookie, disregard this whole topic, i already accepted the solution and I'll leave it as that. Good Night.
Sergey Alexandrovich Kryukov 29-Oct-14 23:40pm
I don't really want to discourage you. Maybe you need to step back to more basic things. This is no rookie. This is few lines of trivial code, could be written in minutes. The developers are supposed to do everything by themselves.
Rate this:
Please Sign up or sign in to vote.

Solution 2

This is the complete solution, with one of the possible options to output the result of conversion:
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';
            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.

[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.


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

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100