Shahroon Farooqi Shahroon Farooqi - 1 year ago 114
C++ Question

Decimal to binary output

method that convert decimal to binary:

string toBinary(unsigned int n) {

char binary[33] = {0}; // char array with 0 value in each index
int ix = 32;

do {
binary[--ix] = '0' + n % 2; // adding remainder to specific index
n /= 2; // dividing n with 2
} while (n); // loop until n is not equal to 0

// return a string
return (binary + ix); // but unable to understand this line

Can anyone please explain what's happening right here
return (binary + ix);

Answer Source

Since ix gets decremented only as long as the loop runs (which changes depending on the magnitude of n), this will truncate the string to not include all of the leading zeros that would be there otherwise.

Also note that you can do this: How to print (using cout) the way a number is stored in memory?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download