Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more elegant way to convert a two-state string into a bitset than just by a 'for' loop?

Tags:

c++

std-bitset

I wrote this code snippet to convert a two-state string ("+++--+-" or "yynnny") into a std::bitset:

#include <bitset>
#include <cstddef>
#include <string>
#include <iostream>

std::bitset<70> convertTwoStateString(std::string twoState)
{
    std::bitset<70> a{0b0};
    std::bitset<70> eins{0b1};

    for(const auto c : twoState) {
        if(c == '+') {
            a <<= 1;
            a |= eins;
        }
        if(c == '-') {
            a <<= 1;
        }
    }
    return a;
}


int main()
{
    std::string s{"-+--+++--+--+"};
    std::bitset<70> set = convertTwoStateString(s);

    std::cout << set << std::endl;
    //0000000000000000000000000000000000000000000000000000000000100111001001
}

Is there a more algorithmic and/or elegant way to do such a conversion?

like image 761
Suslik Avatar asked Nov 19 '25 20:11

Suslik


1 Answers

The std::bitset constructor can specify alternate characters representing 0/1, so you can

std::string s{"-+--+++--+--+"};
std::bitset<70> set(s, 0, s.size(), '-', '+');

Demo

like image 150
康桓瑋 Avatar answered Nov 21 '25 08:11

康桓瑋



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!