0

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];
    }
}
4
  • 1
    I think, you should read about bit manipulations stackoverflow.com/questions/47981/… Commented Apr 7, 2014 at 5:42
  • What's your question? Commented Apr 7, 2014 at 5:43
  • make a string of 64 charcters and set all to zero and then calculate which one should turn to one..supose if my number is 10 then 63 and 61 should turn to one. Commented Apr 7, 2014 at 5:46
  • in that case you want to convert the number to string stackoverflow.com/questions/3702216/… Commented Apr 7, 2014 at 5:48

2 Answers 2

1

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 :).

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

Comments

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

1 Comment

need some editing but got an idea thanks...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.