loop_in_codes

低调做技术__欢迎移步我的独立博客 codemaro.com 微博 kevinlynx

C/c++中几种操作位的方法

参考How do you set, clear and toggle a single bit in C?

c/c++中对二进制位的操作包括设置某位为1、清除某位(置为0)、开关某位(toggling a bit)、检查某位是否为1等。这些操作较为常见并且可以作为其他位运算的基础接口,以下罗列几种方法:

传统方法

  • 设置某位为1
number |= 1 << x; // 设置第x位为1
  • 清除某位
number &= ~(1 << x); // 置第x位为0
  • 开关某位
number ^= 1 << x;
  • 检查某位
if (number & (1 << x))

相应地我们可以将其封装起来,简便的方法是使用宏来封装:

#define BIT_SET(a,b) ((a) |= (1<<(b)))
#define BIT_CLEAR(a,b) ((a) &= ~(1<<(b)))
#define BIT_FLIP(a,b) ((a) ^= (1<<(b)))
#define BIT_CHECK(a,b) ((a) & (1<<(b)))

使用位结构操作

这个使用起来简单很多:

struct bits {
    unsigned int a:1;
    unsigned int b:1;
    unsigned int c:1;
};

struct bits mybits;

// set/clear a bit
mybits.b = 1;
mybits.c = 0;

// toggle a bit
mybits.a = !mybits.a;
mybits.b = ~mybits.b;
mybits.c ^= 1;

// check a bit
if (mybits.c)

使用STL的std::bitset

这个方法其实类似于使用位结构,只不过STL包装了这个结构定义,当然还提供了很多便捷的接口:

std::bitset<5> bits;
bits[0] = true;
bits[1] = false;
bits.set(2);
bits.flip(3);
bits.reset(2);

posted on 2012-09-04 20:29 Kevin Lynx 阅读(4551) 评论(2)  编辑 收藏 引用 所属分类: c/c++tips

评论

# re: C/c++中几种操作位的方法 2012-09-05 09:25 zuhd

小技巧 收藏了  回复  更多评论   

# re: C/c++中几种操作位的方法 2015-04-30 15:06 diefrom

大神你为何这么牛,小弟跟定你了  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理