Question

how to set bits to ON for a number in c++ for example:

for number 0 on 64 bit platform : bits are

00000000 00000000 00000000 00000000

for number 2000000000 on 64 bit platform : bits are

01110111 00110101 10010100 00000000

here is my code so far:

#include<iostream>
#include<limit.h>
const int BIT = CHAR_BIT * CHAR_BIT; // CHAR_BIT states the architecture of platform    
                                     // 8 byte(64 bit) 4 byte(32 bit)
int main()
{
    char* bit = new char[BIT + 1];
    int i;
    for ( i = 0; i < BIT + 1; i++)
        bit[i] = '0';
    unsigned int x;
    cout << "Enter number";
    cin >> x;

    if (x == /* some value */)
    {
        // then calculate which zero's should turn to one as per number
        // or how can i do this using loops
    }
    bit[i] = '\0';


    // displays bit in a specific format
    for (i = 0; i < BIT; i++)
    {
        if ((i % 8) == 0)
        cout << " ";
        cout << bit[i];
    }
}
Was it helpful?

Solution 2

while (x != 0)
{
    std::cout << (x % 2);
    x /= 2;
}

OTHER TIPS

Please read this http://www.math.grin.edu/~rebelsky/Courses/152/97F/Readings/student-binary#dec2bin. It has both the algorithm and sample. Happy learning :).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top