0

I was trying to declare 64bit variable in C with unsigned long long datatype but it not working and behaving similar to uint32 bit variable. What is the solution to access / check the bit above 32 ?

#include <stdio.h>
#include <stdint.h>

int main() {
    // Write C code here
    printf("Hello world");
    unsigned long long temp = 0x1234567890123456ULL;
    unsigned long long temp2 = temp >> 1;
    
    uint64_t var = 0x1234567890123456; 
    
    printf("\n%x", (long long) temp); 
    printf("\n%x", (long long) temp2); 
    printf("\n%x", 1ULL << 31ULL);
    printf("\n%x", 1ULL << 32ULL);
    
    printf("\n%x", var); 
    
    return 0;
}

Output:

Hello world

90123456

48091a2b

80000000

0

90123456

Alex Lop.
  • 6,810
  • 1
  • 26
  • 45
kapilddit
  • 1,729
  • 4
  • 26
  • 51

1 Answers1

8

You used wrong format specifier for printf(). %x is for printing unsigned int. Mismatch in format specifier and actual data in printf() invokes undefined behavior.

To print integers in hexadecimal, you should use %llx for unsigned long long and PRIx64 (from inttypes.h) for uint64_t.

#include <stdio.h>
#include <inttypes.h>

int main() {
    // Write C code here
    printf("Hello world");
    unsigned long long temp = 0x1234567890123456ULL;
    unsigned long long temp2 = temp >> 1;
    
    uint64_t var = 0x1234567890123456; 
    
    printf("\n%llx", (long long) temp); 
    printf("\n%llx", (long long) temp2); 
    printf("\n%llx", 1ULL << 31ULL);
    printf("\n%llx", 1ULL << 32ULL);
    
    printf("\n%" PRIx64, var); 
    
    return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • "To print integers in hexadecimal..." hmm... to me that's not clear/correct. Should it be "To print 64 bit integers...." – Support Ukraine May 31 '21 at 13:55
  • The casts to `long long` should also be removed. The specifier expects `unsigned long long` so we shouldn't pass a `signed long long`. – Nate Eldredge May 31 '21 at 14:42