Is there a built in function in Java that I could use to swap two bits?
For example:
_ _ _ _ 1 _ _ 0 bit 3 swapped with bit 0 and becomes _ _ _ _ 0 _ _ 1
I know it can be done using a long procedure of bit-wise operation, but I want to avoid doing so.
To swap the nibbles, we can use bitwise &, bitwise ” operators. A byte can be represented using a unsigned char in C as size of char is 1 byte in a typical C compiler.
The bitwise XOR operator ( ^ ) returns a 1 in each bit position for which the corresponding bits of either but not both operands are 1 s.
To flip all bits of a binary number you can run loop from 0 to size of the integer and flip individual bit at a time. However, C language has given bitwise complement ~ operator for the purpose. Bitwise complement ~ evaluates complement of the operand bit.
You can also try this way
//positions are indexed from 0 and in order ...[4][3][2][1][0]
//so changing 3 and 1 will make ...[4][1][2][3][0]
public static int swap(int i, int pos1, int pos2) {
int bit1 = (i >> pos1) & 1;// bit at pos1
int bit2 = (i >> pos2) & 1;// bit at pos2
if (bit1 == bit2)
return i; // no need to swap since we change 1 with 1 or 0 with 0
// Since we are here it means that we need to change 1->0 and 0->1.
// To do this we can use XOR (^).
// Lets create mask 000001010 with ones at specified positions
int mask = (1 << pos1) | (1 << pos2);
return i ^ mask;// TADAM!!!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With