Setting bits in 64 bit int
I am trying to set a set of bits in a 64 bit int to. As you can see in the loop basically, I am setting bits 40 through 47 to 1 using the setBit function. for some reason I don't understand that bit 16 to 23 is also set to 1, as you can see from the program output: 000000001111111100000000000000000000000011111111110000000000000000 I couldn't simulate the same behavior on a regular int. BTW I've also tried using unsigned long long instead of int64_t with the same problem. What am I missing?
#include <iostream>
#include <cstdint>
using namespace std;
int64_t x = 0;
void setBit(int64_t *num, int index)
{
*num |= (1 << index);
}
bool retreiveBit(int64_t *num, int index)
{
return *num & (1 << index);
}
int main()
{
for (int i = 40; i < 48; ++i)
setBit(&x, i);
for (int i = 0; i < 64; ++i)
{
int digit = retreiveBit(&x, i);
cout << digit;
}
return 0;
}
source to share
In a subexpression:
(1 << index)
the type of the constant 1
is int
, so this shift is done in int
. If yours is int
not 64 bits wide (it probably isn't), then this shift has undefined behavior.
You need to use a constant at least 64 bits wide:
(1LL << index)
(you need to do this in both functions setBit()
and retrieveBit()
).
source to share