0

I am trying to check the set bits of an unsigned long long in c++ using below algorithm which only checks whether the bit is set or not.But my problem is the answer that I get is wrong.Please help me understand how unsigned long long is stored in binary.

Code:

#include<stdio.h>
#include<iostream>
#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))
using namespace std;
int main()
{
    int pos=sizeof(unsigned long long)*8;
    unsigned long long a;
    cin>>a;
    pos=pos-1;
    while(pos>=0)
    {
        if(CHECK_BIT(a,pos))
          cout<<"1";
        else
          cout<<"0";
        --pos;
    }
}

Input :

1000000000000000000

Output:

1010011101100100000000000000000010100111011001000000000000000000

Expected Output:

110111100000101101101011001110100111011001000000000000000000

Similarly for another input:

14141

Output :

0000000000000000001101110011110100000000000000000011011100111101

Expected Output:

11011100111101

In the second example(in fact for any small number) the binary pattern just repeats itself after 32 bits.

g4ur4v
  • 3,210
  • 5
  • 32
  • 57

1 Answers1

2

I think what you have is an issue in the bit set macro , please replace it w/

#define CHECK_BIT(var,pos) ((var) & (1LL<<(pos)))
Shmil The Cat
  • 4,548
  • 2
  • 28
  • 37
  • 1
    @g4ur4v No problem. BTW please avoid (unsigned long long)*8 , instead of multiply by 8 (kindof magic number) use CHAR_BIT (its more readable) http://stackoverflow.com/questions/3200954/what-is-char-bit – Shmil The Cat Mar 16 '13 at 22:06