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