2015-06-26 39 views
-3

我正在尋找對二進制字符串的一些STL支持。 bitset似乎是非常有用的,但我無法成功操縱單個位。在C++中操縱位集合

#include <iostream> 
#include <bitset> 

using namespace std; 

int main() 
{ 
    string b = bitset<8>(128).to_string(); 

    for(auto &x:b) 
    { 
     x = 1 and x-'0' ; cout<<b<<"\n"; 
    } 

    return 0; 
} 

那麼,我應該使用向量還是bitset可以用於操縱單個位?

上述計劃爲:

☺0000000 
☺ 000000 
☺ 00000 
☺ 0000 
☺ 000 
☺  00 
☺  0 
☺ 

我知道這是因爲我操縱字符,當其設置爲0,打印相關的ASCII字符。我的問題是我可以循環訪問一個bitset並同時修改各個位?

比如,我肯定不能做如下:

#include <iostream>  
#include <string>   
#include <bitset>   
int main() 
{ 
    std::bitset<16> baz (std::string("0101111001")); 
    std::cout << "baz: " << baz << '\n'; 

    for(auto &x: baz) 

    { 
     x = 1&x; 

    } 

std::cout << "baz: " << baz << '\n'; 

    return 0; 
} 
+0

by'and'你想要按位和?如果是,那麼你應該使用'&' – Tempux

+0

Bitset將是最容易操縱個別位。您可以輕鬆地使用[]運算符訪問每一位。 – ChrisD

+0

值得一提的是,'1&x'等價於標識函數,因爲'(1&x)== x',所以這段代碼即使正確也不會修改這些值。 – AlchemicalApples

回答

4

可以使用set,reset,flip, operator[]方法容易操作的std::bitset位。參見http://www.cplusplus.com/reference/bitset/bitset/

// bitset::reset 
#include <iostream>  // std::cout 
#include <string>   // std::string 
#include <bitset>   // std::bitset 

int main() 
{ 
    std::bitset<4> foo (std::string("1011")); 

    std::cout << foo.reset(1) << '\n'; // 1001 
    std::cout << foo.reset() << '\n';  // 0000 

    return 0; 
}