Daryl Dixon
Daryl Dixon

Reputation: 23

DEC to BIN using for and

I have a problem with made a function in c++ that will give me back binary number.

function(unsigned short int user_input, int tab[16]) {
for(ii = 0; ??; ii++)
 tab[ii] = i % 2;
 i = i / 2;
}

User insert DEC number and get back BIN.

Should i just type ii < 16 ? It's working, but is it correct?

Upvotes: 1

Views: 105

Answers (2)

Cameron
Cameron

Reputation: 98776

A somewhat more compact version:

void function(uint16_t x, int b[16]) {
    for (int i = 0; i != 16; ++i, x >>= 1)
        b[i] = x & 1;
}

Note that this puts the least significant bit in b[0].

To answer your question: Yes, ii < 16 is correct. This causes the loop to iterate 16 times, with ii going from 0 to 15 on each execution of the loop body, during which you check the last bit then shift.

Upvotes: 0

mascoj
mascoj

Reputation: 1320

That'll work but is a bit wasteful (if you enter 1, you divide 0 by 2 15 times). Also division by 2 can be "sped up" by shifting. Here's an alternative:

function(unsigned short int user_input, int tab[16]) {
    int idx = 0;
    while(user_input > 0)
    {
        tab[idx] = user_input & 1;
        user_input = user_input >> 1;
        idx++;
    }
    for(; idx < 16; idx++)
    {
        tab[idx] = 0;
    }
}

Upvotes: 1

Related Questions