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];
    }
}
Karedia Noorsil
  • 430
  • 3
  • 9
  • 21
  • 1
    I think, you should read about bit manipulations http://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c-c?rq=1 – fasked Apr 07 '14 at 05:42
  • What's your question? – nobody Apr 07 '14 at 05: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. – Karedia Noorsil Apr 07 '14 at 05:46
  • in that case you want to convert the number to string http://stackoverflow.com/questions/3702216/how-to-convert-integer-to-binary-string-in-c – phuclv Apr 07 '14 at 05:48

2 Answers2

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

0
while (x != 0)
{
    std::cout << (x % 2);
    x /= 2;
}
Spook
  • 25,318
  • 18
  • 90
  • 167