What's the most efficient way to swap any two bits of an integer value in Java?

Andre van Dalen

The "standard" method to swap two bits of an integer involves getting the bit values, shifting them into the other position, masking the rest of the number value and or-ing the newly positioned values into place.

An example of this is given below in the method swapbit1. When the bit positions are known in advance, you should let the compiler do all the hard work and define final int constants for the bit positions, the mask and the shift (this is left as an exercise for the reader ;-).

When you realise that bits can contain only 2 values, and that they can be flipped using the XOR operator ^, a simpler and therefore more efficient way is to check that the two bits in question are different and when they are flip their values, this is done in swapbit2 below. (Note that if they have equal values it makes no sense doing anything.)

The following code gives an example for both methods:
public class swapbit {
  public static void main(String[] argv) throws NumberFormatException {
    int number = argv.length < 1 ? 0xff00 : Integer.parseInt(argv[0]);
    int bit1 = argv.length < 2 ? 1 : Integer.parseInt(argv[1]);
    int bit2 = argv.length < 3 ? 9 : Integer.parseInt(argv[2]);

    System.out.println("Swapbit1(" + Integer.toHexString(number) + 
      ", " + bit1 + ", " + bit2 + ") = " +
    Integer.toHexString(swapbit1(number, bit1, bit2)));
    System.out.println("Swapbit2(" + Integer.toHexString(number) + 
      ", " + bit1 + ", " + bit2 + ") = " +
    Integer.toHexString(swapbit2(number, bit1, bit2)));
  }

  // needs bit2 > bit1, bit position based 0
  public static int swapbit1(int number, int bit1, int bit2) {
    int shift;
    if (bit1 > bit2) {
      shift = bit2;
      bit2 = bit1;
      bit1 = shift;
    }
    shift = bit2 - bit1;
    int bit1pos = 1 << bit1;
    int bit2pos = 1 << bit2;
    int mask = ~(bit1pos | bit2pos);

    return (number & mask) | ((number & bit1pos) << shift) | 
      ((number & bit2pos) >> shift);
  }

  // bit position based 0
  public static int swapbit2(int number, int bit1, int bit2) {
    int bit1pos = 1 << bit1;
    int bit2pos = 1 << bit2;

    if ((number & bit1pos) == 0 ^ (number & bit2pos) == 0) {
      number ^= bit1pos | bit2pos;
    }

    return number;
  }
}

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact