你如何设置,清除和切换一个位?如何在C / C ++中设置,清除和切换?
                    
                    
                3 回答
 
                    
                    
                            神不在的星期二
                            
                                
                            
                        
                        
                                                
                    TA贡献1963条经验 获得超6个赞
使用标准C ++库:std::bitset<N>。
或Boost版本:boost::dynamic_bitset。
没有必要自己动手:
#include <bitset>#include <iostream>int main(){
    std::bitset<5> x;
    x[1] = 1;
    x[2] = 0;
    // Note x[0-4]  valid
    std::cout << x << std::endl;}[Alpha:] > ./a.out00010
与标准库编译时大小的bitset相比,Boost版本允许运行时大小的bitset。
 
                    
                    
                            人到中年有点甜
                            
                                
                            
                        
                        
                                                
                    TA贡献1895条经验 获得超7个赞
另一种选择是使用位字段:
struct bits {
    unsigned int a:1;
    unsigned int b:1;
    unsigned int c:1;};struct bits mybits;定义一个3位字段(实际上,它是三个1位字符)。位操作现在变得有点(哈哈)更简单:
设置或清除一下:
mybits.b = 1;mybits.c = 0;
要切换一下:
mybits.a = !mybits.a;mybits.b = ~mybits.b;mybits.c ^= 1; /* all work */
检查一下:
if (mybits.c) //if mybits.c is non zero the next line below will execute
这仅适用于固定大小的位字段。否则你必须采用之前帖子中描述的比特技巧。
- 3 回答
- 0 关注
- 822 浏览
添加回答
举报
0/150
	提交
		取消
	