4

From following code I expect to set all bits in x to 1, but somehow only first 32 bits are set:

int64_t x = 0xFFFFFFFF;
x<<32;
x|=0xFFFFFFFF;

Note: printing x after each line results in 4294967295 (32 lower bits set to 1). Also, tried using numeric_limits<int64_t>::min() with no success. My question is how to set all bits in x? Using RHEL5.5.

Thx

R_N
  • 111
  • 9
  • 2
    How are you printing it? – Mysticial May 02 '13 at 23:15
  • 1
    If all else fails, and I really mean all because it's not pretty, `memset(&x, 0xFF, 8)`. – ssube May 02 '13 at 23:15
  • building a streamstring and printing it, no precision. Assume prints are ok, I "see" it wrong in calculations later in code – R_N May 02 '13 at 23:16
  • @peachykeen : trying to avoid memset, but still I will try, thanks – R_N May 02 '13 at 23:18
  • 1
    If you care about the bits, why are you using `int64_t` rather than `uint64_t`? (And `x<<32` doesn't work because you're discarding the result; you wanted `x <<= 32`.) But shifting a `1` into the sign bit position has undefined behavior -- thus my question about `uint64_t`. – Keith Thompson May 02 '13 at 23:25
  • Not a dupe, but see this question: http://stackoverflow.com/questions/809227/is-it-safe-to-use-1-to-set-all-bits-to-true – Adrian McCarthy May 02 '13 at 23:26

3 Answers3

14

x<<32 calculates the result of shifting x left by 32 bits and does nothing with the value. You want to use x <<= 32 instead.

jwodder
  • 54,758
  • 12
  • 108
  • 124
  • jwodder has what you want OP. You forgot to assign your result: x = x << 32; as opposed to what you had. – Xathereal May 02 '13 at 23:19
  • As an aside, it's technically undefined behavior because of overflow –  Jun 30 '16 at 11:30
10

Why not int64_t x = -1? or uint64_t x = ~0?

paulsm4
  • 114,292
  • 17
  • 138
  • 190
4

This will work:

int64_t x = ~0LL;   (iner

or

int64_t x = -1LL;

You may get away with not having the LL, but not guaranteed - depends on the compiler.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • 1
    And also, you may get away with having the LL :) ("depends on the compiler", though 128-bit long long isn't coming for a while) – Nicholas Wilson May 02 '13 at 23:39