gsamaras gsamaras - 8 days ago 5
C++ Question

3 ways to toggle a bit represented as a char

I wrote this:

#include <iostream>
#include <vector>

int main()
{
std::vector<char> v = {0, 0, 0};
v[0] = v[0] == 0 ? 1 : 0;
v[1] = !v[1];
v[2] ^= 1;
std::cout << (int)v[0] << (int)v[1] << (int)v[2] << "\n";
return 0;
}


which toggles all bits, but I actually care on changing only the i-th bit.

What am I interested in is which one of these ways should one use in a project, when the only thing that you care is speed (not memory and readability)?




The reason for using
std::vector<char>
as a bitset is that in my timings I found that it's faster than a vector of
int
s or
char
s, and
std::bitset
.

Answer

You can instead use either std::bitset as long as you are interested in bits or use directly vector of bool not char:

#include <iostream>
#include <vector>

int main()
{
    std::vector<bool> v = { 0, 0, 0 };

    for (int i(0); i < v.size(); i++)
        v[i] = !v[i];

    for (int i(0); i < v.size(); i++)
        std::cout << (int)v[i];

    std::cout << std::endl;

    std::cin.get();
    return 0;
} 
  • the bitwise not ! is recommended due to its speed and cleanness.
Comments