BIT Manipulation #1 dec to binary

#include <bits/stdc++.h>
using namespace std;
 
int main(){
    
    //convert a decimal into binary uwsing bitwise:
    int num = 233;

    bool start = false;
    for(int c = 31;c>=0;c--){
        int res = num >> c;

        if(res & 1){
            start = true;
            cout << 1;
        }
        else if(start) cout << 0;

    }

    // for(int i=31;i>=0;i--){
    //     int res = num & (1<<i);
    //     if(res) cout << 1;
    //     else cout << 0;
    // }




//   The first time, the value of c is 31.

// Assuming the bit representation of decimal_num initially is x................................ ( . represents any digit )

// decimal_num >> 31 shifts all bits rightwards 31 times, such that the first bit is shifted at the right most end. The result is 0000000000000000000000000000x. Note that when digits are shifted, 0 is pre-pended to the left end.

// The result is then checked to see if it was 0 or 1, and printed accordingly. 0000000000000000000000000000x & 00000000000000000000000000001 = 1 if x is one 0000000000000000000000000000x & 00000000000000000000000000001 = 0 if x is zero.

// Moving on, and checking the second bit when c is 30. :

// .Y..............................

// decimal_num >> 30 results in 000000000000000000000000000000.Y

// 000000000000000000000000000.Y & 00000000000000000000000000001 = 1 if Y is one 000000000000000000000000000.Y & 00000000000000000000000000001 = 0 if Y is zero.

// We go on printing the results until the last digit.


    return 0;
}

Comments

Popular Posts