0

I have some trouble with a C program that does some bit manipulation. In the program, I use an unsigned long long int variable to represent a 64 bit map, each bit representing a position on the map. I need to be able to update these bits (positions) i.e. setting or clearing a bit. To clear and set a bit, I do (0 is the least significant position):

map &= ~(1 << pos) // clear bit in position 'pos' map |= (1 << pos) // set bit in position 'pos' 

The problem is that when i perform these operations, all the bits in the map which are to the left of pos get set to 0 (while I want only the bit in position pos to change).

What am I doing wrong?

2
  • 1
    Try using 1ULL to ensure the mask is the correct size. Commented Nov 14, 2015 at 17:30
  • 1
    This has been asked before, several times. The problem is the type of the 1. Commented Nov 14, 2015 at 17:30

1 Answer 1

5

The problem is that those shifts are done using the type int, which on all modern 64-bit systems are still 32 bits. You need to use the same type as map, i.e. unsigned long long:

1ull << pos 

Note the ull which tells the compiler that the 1 is not an int but an unsigned long long.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. I knew it was something with the data types, but I didn't know how to make the shifts with the same type as the map.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.