Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting bits in a 64bit int

Tags:

c++

I am trying to set a set of bits in a 64 bit int to ones. As you can see in the loop in main I'm setting bits 40 to 47 to 1 using the setBit function. for a reason I don't understand bits 16 to 23 are also set to 1 as you can see from the program's output: 0000000011111111000000000000000000000000111111110000000000000000 I couldn't mimic the same behavior on a regular int. BTW I also tried using a 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;
}
like image 995
Benny Abramovici Avatar asked Apr 01 '26 04:04

Benny Abramovici


1 Answers

In the sub-expression:

(1 << index)

the type of the constant 1 is int, so this shift is done in an int. If your int isn't 64 bits wide (it probably isn't), then this shift has undefined behaviour.

You need to use a constant that is at least 64 bits wide:

(1LL << index)

(you need to do this in both the setBit() and retrieveBit() functions).

like image 130
caf Avatar answered Apr 02 '26 20:04

caf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!