0

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

4
  • web.math.princeton.edu/math_alive/1/Lab1/Conversion.html Commented Nov 30, 2016 at 13:40
  • thanks for replay guys. Can you please explain it little bit more Commented Nov 30, 2016 at 13:41
  • Small comment: int is not necessarily 32 bit, which is assumed here. bigger numbers will have a strange effect here. The solution is to use sizeof(int)*CHAR_BIT instead of 32. Commented Nov 30, 2016 at 14:12
  • As usual there is no decimal to binary conversion here. n is already binary. All you're doing is changing to a printable representation. Commented Aug 29 at 1:02

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.