Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Have some doubts in the operation [Bitwise Manipulation]

#include <iostream>
#include <math.h>
using namespace std;

// converting from decimal to binary

int main()
{
    int n, bit, ans = 0, i = 0;
    cout << "enter a number: ";
    cin >> n;
    while (n > 0)
    {
        bit = n & 1;
        ans = round(bit * pow(10, i)) + ans; /* we used 'round' bcoz pow(10, 2) give 99.99999
                                                it differs from compiler to compiler  */
        n = n >> 1;
        i++;
    }

    cout << ans;
    return 0;
}

I am unable to understand that in while(n>0), n will be stored as binary form or decimal form.
That is if n=5, so whether while loop check for (5>0) or (101>0).

Can anyone explain what is happening here?

I am new to this platform, please don’t delete my question. My earlier questions are also gets deleted due enough dislikes. I am here to learn and am still learning.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

"Decimal" and "Binary" are text representations of a value. n is an int, not text, so it holds the value 5. If I have 5 apples on a desk, then there is no "decimal" or "binary" involved. THere’s just 5 apples. Same with int.

cin >> n;
while (n > 0)

This loop continues because 5 > 0.

n = n >> 1;

This is just a fancy way of writing n = n / 2, so then n becomes 2. Since 2 > 0, the loop continues. On the third run, n becomes 1, and since 1 > 0, the loop continues a third time. On the fourth run, n becomes 0, and 0 == 0, so the while loop exits.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading