1

I have the following code:

#include <stdio.h>

int main() {
  long long int x = 4294967296;
  long long int y = 2^32; // 4294967296
  printf("%lld \n", x);
  printf("%lld \n", y);
}

It outputs:

4294967296
34

This is a contrived example but how can I force an arithmetic expression to a wider type? I tried something like

(2LL)^(32LL)

but does not work. I'm compiling with gcc on 64-bit Ubuntu.

.

// EDIT

Obviously I'm a noob and did not realize ^ is not the exponential operator but bitwise XOR... I'll now shamefully go back to learning C

gws
  • 767
  • 1
  • 8
  • 15

2 Answers2

1

As others noted ^ is exclusive or, in most languages.

The best way to compute an integer power of 2 is to use bit shifting, not floating point pow as you could lose precision (for powers of other numbers there are good algorithms too: The most efficient way to implement an integer based power function pow(int, int)).

But for that you have to make sure the result doesn't overflow.

#include <stdio.h>

int main()
{
   long long int y = 1LL<<32;

   printf("%lld\n",y);

}

The other trap here is that you cannot shift 1 32 times without using the LL prefix, otherwise overflow occurs before assigning to long long (see Overflow appears even when using unsigned long int) unless the int type is 64 bit. I wouldn't bet on it, and most compilers warn you about the overflow anyway.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

first, the result you got is correct because you are actually XORing the value

second, at least in your case you can shift the output by 32 but in that case you need to make sure that the value you are about to shift is at least 64bit long in order to prevent overflow hence you nust use something like:

unsigned long long test = 1LLU << 32;

note the LLU where the '2' primitive is set to at-least 64bit width before the shift. casting in this case won't work since the calculated output already overflowed

Omer Dagan
  • 662
  • 5
  • 14