C - Swap the place between two numbers

I just tried with this code:

void swapBit(unsigned char* numbA, unsigned char* numbB, short bitPosition)//bitPosition 0-x
{
    unsigned char oneShift = 1 << bitPosition;

    unsigned char bitA = *numbA & oneShift;
    unsigned char bitB = *numbB & oneShift;

    if (bitA)
        *numbB |= bitA;
    else
        *numbB &= (~bitA ^ oneShift);

    if (bitB)
        *numbA |= bitB;
    else
        *numbA &= (~bitB ^ oneShift);
}

      

to swap bit position of xa and b, but because of the if () I think something is better.

Also when I see this:

*numbB &= (~bitA ^ oneShift);

      

I really think there is an easier way to do this. If you have something for me I would take it :)

Thank you in advance

+3


source to share


2 answers


You must first set the corresponding position in the count 0

and then OR with the actual bit, removing all conditions:

*numbB &= ~oneShift; // Set the bit to `0`
*numbB |= bitA;      // Set to the actual bit value

      



The same for the other number.

+5


source


Create a mask

unsigned char mask = 1u << bitPosition;

      

And then earn the wrath of your peer group with the XOR exchange algorithm .



*numbA ^= *numbB & mask;
*numbB ^= *numbA & mask;
*numbA ^= *numbB & mask;

      

Note that this fails if numbA == numbB

.

0


source







All Articles