Skip to content

To binary

C++ decimal → binary

Flowchart (ISO 5807)

YesNoYesNoStartInput nn = 0Output 0ReturnEndk = 0n > 0bits[k] = n mod 2n = n / 2k = k + 1i = k − 1, 0, −1Output bits[i]EndFigure 1 — toBinary

Source code

C++
void toBinary(int n) {
    if (n == 0) {
        cout << 0;
        return;
    }
    int bits[32];
    int k = 0;
    while (n > 0) {
        bits[k] = n % 2;
        n /= 2;
        k++;
    }
    for (int i = k - 1; i >= 0; i--) cout << bits[i];
}

The editor opens with this code — change it and the chart redraws.

Language
C++
Constructs
decimal → binary
Topic
Algorithms
Formats
Word, Visio, draw.io, PDF, SVG

Related examples