1

I want to set bit in a long long int number on a 64 bit machine. Example, i want to set bit at element 18 19, i use the following code:

A1 |= 1 << 2 * i;  // i = 9 , set bit 18 =1, A1 long long int
A1 &= ~(1 << 2 * i + 1); //clear bit 19 = 0

but it doesn't work. If i do it for long int, it works fine.

  • 1
    The shifted `1` should be `long long` too, so maybe `1LL`. – pascal Mar 23 '15 at 15:32
  • 1
    To set both bits 18 and 19 why not simply use e.g. `A1 |= (1LL << 18 | 1LL << 19)`. – Some programmer dude Mar 23 '15 at 15:34
  • "it doesn't work" is a vague description of a problem, inviting people to guess what the actual problem is. It would be better to post a complete program, which outputs an unexpected value, and state what the expected value is. See also [mcve](http://stackoverflow.com/help/mcve) – anatolyg Mar 23 '15 at 15:38
  • 2
    Consider using `std::bitset`, which performs some safety checking in good debug compilers. – Neil Kirk Mar 23 '15 at 15:39
  • Related to [this question](http://stackoverflow.com/questions/8809292/ull-suffix-on-a-numeric-literal)? – pascal Mar 23 '15 at 15:39
  • You should do what @Joachim or Neil suggested, because, as you have it written now, nobody would have the slightest clue what you're trying to accomplish without reading the comments. Even then, it's still unnecessarily obfuscated. – Julian Mar 23 '15 at 15:48
  • thanks pascal mcve-anatolyg Joachim. Joachim, because it in a loop, and I want to set a bit and clear a bit so I seperate 2 part to do and use "i". Do you have any ideal to set and clear it at the same time. – An Nguyễn Mar 23 '15 at 15:59
  • NeilKrik I can't use bitset because i set bit in CUDA. – An Nguyễn Mar 23 '15 at 16:00

1 Answers1

5

The literal 1 has type int, which is probably smaller than long long. You'll get undefined behaviour (typically a value of zero) if you shift by enough bits to overflow the int type; and the second line will (probably) clear any bits present in A1 but not in an int value.

Use 1LL to specify a long long type, or decltype(A1)(1) to specify a type that matches A1.

In general, it's usually best to use unsigned types (unsigned long long or perhaps uint64_t in this case) for bit-wrangling. Use 1ULL to get a literal of type unsigned long long.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644