Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I swap two bits of integer in Java?

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.

like image 867
waheebyaqub Avatar asked Apr 10 '13 14:04

waheebyaqub


People also ask

How do you swap nibbles in assembly?

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.

What is the output of the code if operator is Bitwise XOR?

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.

How do you bit flip in C?

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.


1 Answers

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!!!
}
like image 97
Pshemo Avatar answered Oct 15 '22 00:10

Pshemo