Search code examples
cbit

Bits mirroring in memory


When i'm trying to print every bit in a number stored in uint64_t the bits are the same after bit number 32.

For example if i have read 3 which is 011 when i print it is 1100000...11000000. The number appears to be "mirrored" after bit number 32. When i'm printing the number with printf it is 3 Why is this happening?

long long int memory;
scanf("%lld",&memory);
for(int i = 63;i>=0;i--){
       long long int nr = (1<<i);
       if((memory & nr)==0)
          printf("%d",0);
        else
          printf("%d",1);
   }

Solution

  • In 1<<i, 1 is an int, and the expression is not defined by the C standard when the value of i is the number of bits in an int or greater.

    Change it to (unsigned long long int) 1 << i or 1ull << i. (This presumes your C implementation uses two’s complement, which essentially all modern implementations do. Otherwise, examining the bits of signed integers is a bit trickier.)