0

I have to write a c++ function which swaps nth and least significant bit of an int. I found some examples and did this:

v1 = v1 ^ ((((v1&1) ^ (v1>>n)&1) << LSBpos) | (((v1&1) ^ (v1>>n)&1) << n));
cout<<v1;

v1 is an int. v1&1 is the value of LSB. LSBpos should be the position of LSB but I don't know how to get it. There are explanations of how to get the position of LSB that is set or clear, but I just need that position, whether it is set or not.

1 Answers1

2

You don't need to know the position of the LSB. And this is great because due to endianness it could be at multiple places!

Let us find some help: How do you set, clear, and toggle a single bit?:

Checking a bit

You didn't ask for this, but I might as well add it. To check a bit, shift the number n to the right, then bitwise AND it:

bit = (number >> n) & 1U;

Changing the nth bit to x

Setting the nth bit to either 1 or 0 can be achieved with the following on a 2's complement C++ implementation:

number ^= (-x ^ number) & (1UL << n);

And go for it!

int swap_nth_and_lsb(int x, int n)
{
    // let to the reader: check the validity of n

    // read LSB and nth bit
    int const lsb_value = x& 1U;
    int const nth_value = (x>> n) & 1U;

    // swap
    x ^= (-lsb_value) & (1UL << n);
    x ^= /* let to the reader: set the lsb to nth_value */

    return x;
}

In the comment, OP said "I have to write one line of code for getting result". Well, if the one-line condition holds, you can start from the above solution and turn it into a one-liner step by step.

Community
  • 1
  • 1
YSC
  • 38,212
  • 9
  • 96
  • 149