Flip the bits with XOR 0xffffffff or ~ in C ++?

If I want to flip a few bits, I was wondering which way is better. Should I flip them with XOR 0xffffffff

or with help ~

?

I'm afraid there will be times when I might need to stuff the bits at the end in one of these ways rather than the other, which would make the other way safer. I am wondering if there are times when it is better to use one over the other.

Here is code that uses both values ​​for the same input value, and the output values ​​are always the same.

#include <iostream>
#include <iomanip>

void flipBits(unsigned long value)
{
    const unsigned long ORIGINAL_VALUE = value;
    std::cout << "Original value:" << std::setw(19) << std::hex << value << std::endl;

    value ^= 0xffffffff;
    std::cout << "Value after XOR:" << std::setw(18) << std::hex << value << std::endl;

    value = ORIGINAL_VALUE;
    value = ~value;
    std::cout << "Value after bit negation: " << std::setw(8) << std::hex << value << std::endl << std::endl;
}

int main()
{
    flipBits(0x12345678);
    flipBits(0x11223344);
    flipBits(0xabcdef12);
    flipBits(15);
    flipBits(0xffffffff);
    flipBits(0x0);
    return 0;
}

      

Output:

Original value:           12345678
Value after XOR:          edcba987
Value after bit negation: edcba987

Original value:           11223344
Value after XOR:          eeddccbb
Value after bit negation: eeddccbb

Original value:           abcdef12
Value after XOR:          543210ed
Value after bit negation: 543210ed

Original value:                  f
Value after XOR:          fffffff0
Value after bit negation: fffffff0

Original value:           ffffffff
Value after XOR:                 0
Value after bit negation:        0

Original value:                  0
Value after XOR:          ffffffff
Value after bit negation: ffffffff

      

+3


source to share


2 answers


Use ~

:



  • You will not rely on any particular type width; for example, int

    not 32 bits on all platforms.
  • Eliminates the risk of accidentally entering one f

    too few or too many.
  • This makes the intent clearer.
+10


source


How do you ask specifically, just use std::bitset

#include <iostream>
#include <iomanip>
#include <bitset>
#include <limits>

void flipBits(unsigned long value) {
    std::bitset<std::numeric_limits<unsigned long>::digits> bits(value);
    std::cout << "Original value : 0x" << std::hex << value;

    value = bits.flip().to_ulong();
    std::cout << ", Value after flip: 0x" << std::hex << value << std::endl;
}

      



Watch live demo .

As for your mentioned problems, just use the ~

value operator unsigned long

and have more bits flipped as needed:
Since std::bitset<NumberOfBits>

it actually specifies the number of bits on which it should run, it correctly solves such problems.

+4


source







All Articles