Reputation: 3288
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.
Upvotes: 0
Views: 1735
Reputation: 4668
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)))
Upvotes: 2