C语言 - 位运算置0操作

来源:互联网 发布:面试算法题 编辑:程序博客网 时间:2024/05/16 00:36

位运算置0操作


本文地址: http://blog.csdn.net/caroline_wendy/article/details/26733313


C语言与C++的不同, 关键在于位运算宏操作, 可以通过位移(<<)与运算(&), 把指定位置为0.


代码:

/* * test.cpp * *  Created on: 2014.05.23 *      Author: Spike *//*eclipse cdt, gcc 4.8.1*/#include <iostream>#define BIT_MASK(bit_pos) (0x01 << (bit_pos))using namespace std;int Bit_Reset(unsigned int* val, unsigned char pos) {if (pos >= sizeof(unsigned int)*8) {return 0;}*val = (*val & ~BIT_MASK(pos)); //与0做与(&)运算return 1;}int main() {unsigned int x = 0xffffffff;unsigned char y = 4;Bit_Reset(&x, y);std::cout << std::hex << x << std::endl;return 0;}

输出:

ffffffef





8 0