0

In a c program. I am trying to use the left shift operator on uint64_t variable.

E.g.

 // with shift of 24 bits uint64_t x = 0; x = (((uint64_t)76) << (24)); Output is: x = 1275068416 --------------------------------------------- // with shift of 32 bits uint64_t x = 0; x = (((uint64_t)76) << (32)); Output is: x = 0 

If I perform left shift till 24 bits then it works fine, but at 32 bits it outputs 0. Whereas what I think is as the size of uint64_t i.e. unsigned long long is 64 bits. So shouldn't it work till the 64 bit shift ?

6
  • 2
    What construct do you use to examine the value of x? Commented Feb 25, 2016 at 18:06
  • I am just printing out the value of x using printf as printf("....%d\n", x); Commented Feb 25, 2016 at 18:07
  • 2
    QED, then.. %d is working for ints. Use "%llu" Commented Feb 25, 2016 at 18:09
  • 4
    Ah, that's just that. To print a value of type uint64_t you need printf("%"PRIu64"\n", x);. Commented Feb 25, 2016 at 18:09
  • @EugeneSh. and Andrey Chernyakhovskiy ... thanks it works as suggested by both of u :-) Commented Feb 25, 2016 at 18:11

1 Answer 1

2

You're using the wrong format specifier to print the output. The %d format specifier expects an int, which apparently is 32-bit on your system. So passing a 64-bit value (and an unsigned one at that) leads to undefined behavior.

You should use the PRIu64 macro to get the correct format specifier for an unsigned 64-bit value.

printf("%"PRIu64"\n", x); 
Sign up to request clarification or add additional context in comments.

2 Comments

%lu is solely reserved for unsigned long. On a Windows machine that's typically 32 bits.
@AndreyChernyakhovskiy Thanks. Edit applied.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.