Shahroon Farooqi
Shahroon Farooqi

Reputation: 103

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

Upvotes: 1

Views: 300

Answers (2)

Andrew
Andrew

Reputation: 518

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?

Upvotes: 1

Sam Varshavchik
Sam Varshavchik

Reputation: 118292

ix is an index into the char array. The function creates the binary string starting with its rightmost bit, near the end of the array, and working its way towards the beginning of the array, creating each bit one at a time.

Therefore, when the last bit is created, ix points to the index of the first, most-significant bit. It's not always going to be at the beginning of the array: specifically it won't be if there were fewer than 32 bits.

"binary + ix" adds the index to the first bit to the start of the char buffer, calculating a pointer to the first bit. Since the function returns a std::string, this is fed to std::string's constructor, which takes the pointer to a literal string and constructs a full std::string object from it, implicitly.

Upvotes: 2

Related Questions