# toggle bit in unsigned long var

• 02-19-2011
thescratchy
toggle bit in unsigned long var
Hello,

I want to toggle bits in an unsigned long variable. But I get an overflow with bits higher then 31.
Any ideas how to solve this? Thank you.

Code:

``` unsigned long n = 63; unsigned long c = 0x8000000000000000; c ^= (1 << n); Output: 01111111 | 11111111 | 11111111 | 11111111 | 10000000 | 00000000 | 00000000 | 00000000```
• 02-19-2011
Elysia
Of course you do. Typically, a long is 32 bits long.
• 02-19-2011
thescratchy
If I change my code to the following:

Code:

```unsigned long long n = 63; unsigned long long c = 0x8000000000000000; c ^= (1 << n);```
shouldn't it work then? I still have the same problem.
• 02-19-2011
brewbuck
Quote:

Originally Posted by thescratchy
If I change my code to the following:

Code:

```unsigned long long n = 63; unsigned long long c = 0x8000000000000000; c ^= (1 << n);```
shouldn't it work then? I still have the same problem.

The value "1" is 32 bits. You shift that left 63 and you get zero. Write "1LL" instead.
• 02-19-2011
Elysia
This works as expected:
Code:

```int main() {         unsigned long long n = 63;         unsigned long long c = 0x8000000000000000;         unsigned long long mask = 1ull << n;         c ^= mask; }```
Also, IIRC, shifting a signed number is implementation defined.
EDIT: More exactly, shifting a negative signed number is either implementation defined or undefined, so avoid it.
• 02-19-2011
thescratchy
Thank you guys for your help
• 02-19-2011
kona49er
Quote:

Originally Posted by thescratchy
If I change my code to the following:

Code:

```unsigned long long n = 63; unsigned long long c = 0x8000000000000000; c ^= (1 << n);```
shouldn't it work then? I still have the same problem.

Try:
Code:

```     c ^= (1ull << n);```
• 02-19-2011
Sebastiani
Quote:

Originally Posted by kona49er
Try:
Code:

```     c ^= (1ull << n);```

Better yet:

Code:

```#include <limits> template < typename Integer > Integer msb( void ) {     static Integer msk = Integer( 1 ) << sizeof( Integer )         * std::numeric_limits< unsigned char >::digits - 1;     return msk; } // Example: #include <iostream> int main( void ) {     using namespace std;     cout << int( msb< unsigned char >( ) ) << endl;     cout << msb< short >( ) << endl;     cout << msb< unsigned long >( ) << endl; }```