Removing Bits – Two Methods


For example, if you want to remove a bit or some bits from a integer (signed or unsigned), you can do this.

1
2
3
4
5
6
7
inline
int removeBit(int n, int bit) {
  if ((n & bit) == bit) {
    return n - bit;
  }
  return n;
}
inline
int removeBit(int n, int bit) {
  if ((n & bit) == bit) {
    return n - bit;
  }
  return n;
}

Several bits can be combined for example 7 means 00000111 (binary). Only all these bits are set will they be removed from the input. A faster way without branch (if statement) is:

1
2
3
4
inline
int removeBit(int n, int bit) {
  return n & (~bit);
}
inline
int removeBit(int n, int bit) {
  return n & (~bit);
}

We use bitwise NOT to get the pattern, for example 7 bitwise not returns 11111000 (binary), and then we can use bitwise and to remove the bits. Please not that it does not require all bits are set. The task is to make sure these bits are clear after the operation. The first approach will only clear the bits if they are already set.

In most cases, the second method is enough and it is faster.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
206 words
Last Post: Ternary Operator and Boolean
Next Post: How to Change the Priority of Network Adapters Under Win8 ?

The Permanent URL is: Removing Bits – Two Methods

Leave a Reply