# Thread: toggle bit in unsigned long var

1. ## 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```

2. Of course you do. Typically, a long is 32 bits long.

3. 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.

4. 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.

5. This works as expected:
Code:
```int main()
{
unsigned long long n = 63;
unsigned long long c = 0x8000000000000000;
unsigned long long mask = 1ull << n;
}```
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.

6. Thank you guys for your help

7. 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);`

8. 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;
}```