Question

I am trying to manipulate 64 bits. I use the number to store in an unsigned long long int.To test the porcess I ran the following program

#include <iostream>

using namespace std;

int main()
{
 unsigned long long x = 1;
 int cnt = 0;
 for(int i =0 ;i<64;++i)
 {
    if((1<<i)&x)
    ++cnt;
 }
 cout<<cnt;
 }

but the output of the cnt is 2 which is clearly wrong. How Do I manipulate 64 bits? where is the correction? Actually I am trying to find parity, that is number of 1's in binary representation of a number less than 2^63.

Was it helpful?

Solution

For it's 64-bit, you should use a 64-bit 1. So, try this:

if(((unsigned long long) 1<<i)&x)

OTHER TIPS

(1<<i) will overflow when i greater than 32

you can write the condition like (x >> i) & 1

What is meant by manipulation in your case? I am thinking you are going to test each and every bit of variable x. Your x should contain maximum value because you are going to test every bit of your variable x

int main()
{
 unsigned long long x = 0xFFFFFFFFFFFFFFFF;
 int cnt = 0;
 for(int i =0 ;i<64;++i)
 {
    if((1<<i)&x)
    ++cnt;
 }
 cout<<cnt;
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top