Example #1
0
  public void flip(int fromIndex, int toIndex) {
    checkRange(fromIndex, toIndex);

    int length = length();

    // if we are flipping bits beyond our length, we are setting them to
    // true
    if (fromIndex >= length) {
      set(array, fromIndex, toIndex);
      return;
    }

    // check to see if toIndex is greater than our array length
    if (toIndex >= length) {
      set(array, length, toIndex);
      toIndex = length;
    }

    int first = wordIndex(fromIndex);
    int last = wordIndex(toIndex);
    int startBit = bitOffset(fromIndex);
    int end = bitOffset(toIndex);

    if (first == last) {
      // flip the bits in between first and last
      flipMaskedWord(array, first, startBit, end);

    } else {
      // clear the bits from fromIndex to the next 32 bit boundary
      if (startBit != 0) {
        flipMaskedWord(array, first++, startBit, 32);
      }

      // clear the bits from the last 32 bit boundary to the toIndex
      if (end != 0) {
        flipMaskedWord(array, last, 0, end);
      }

      // flip everything in between
      for (int i = first; i < last; i++) {
        flipWord(array, i);
      }
    }
  }