Decimal to Binary

How to convert a decimal into a binary number? I have come up with this code, but it prints the binary in reverse order, how do I get the correct order?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    int integer, value;
    float quotient, remainder;
    
    cout << "Enter int value: ";
    cin >> value;
    cout << "The binary representation of " << value << " is: ";
    for(integer = 0; integer < 32; integer++) {
        quotient = value / 2;
        remainder = value % 2;
        cout << remainder;
        value = quotient;
    }
    cout << endl; 

    return 0;
    
}
If you only want it as a binary value for displayed output (in form of a string) then use the _itoa_s() function.
The original function is itoa() but some reason it got changed a lot because of security issues or something?!

1
2
3
4
5
void outputAsBinary(int value){
    char buffer[32]; //Capable of holding a full 32 bit int
    _itoa_s(value, &buffer, 2) //Args: Numerical value, string to write to, base to convert to
    cout << buffer;
}


Or if you want to stay within your own code and not use the string library you probably could just reverse your loop order and add a few little tweaks.
1
2
3
4
5
6
int value;
char[32] buffer = {0};
for(int i = 0x80000000, j=0; i>1; i/=2, j++){
    if(value & i)
        buffer[j] = 1;
}

(I think this should work, I'm afraid I don't have time to double check this one as I'm in a bit of a hurry now)

If you want the value written as binary then that is already done, you just need to use the correct syntax to access it in this format. (bitwise operators)

EDIT: Sorry. I meant to put those 1s add 0s inside character syntax '1'
Last edited on
store your remainder in a string before you cout them
Topic archived. No new replies allowed.