1. 程式人生 > >將整數的第n位清零或置1,其他位不變

將整數的第n位清零或置1,其他位不變

假設有一個整數為x,編寫兩個函式將x的二進位制位的第n位置1或清零,其他位不變 如有x=10,二進位制表示為:00000000 00000000 00000000 00001010,二進位制位的最右邊稱為第一位,比如將第二位的1清為0,則為:00000000 00000000 00000000 00001000 = 8, 將第三位置為1,則為:   00000000 00000000 00000000 00001110 = 14。 程式碼實現為:
  1. #include <iostream>
  2. using namespace std;
  3. #define IBS(n) 0x01<<(n-1)
  4. void Set_N_To_1(int &x, int n)
  5. {
  6.     x |= IBS(n);
  7. }
  8. void Clear_N_To_0(int &x, int n)
  9. {
  10.     x &= ~IBS(n);
  11. }
  12. int main()
  13. {    
  14.     int x = 10;
  15.     Set_N_To_1(x, 3);
  16.     cout<<x<<endl;
  17.     x = 10;
  18.     Clear_N_To_0(
    x, 2);
  19.     cout<<x<<endl;
  20.     return 0;
  21. }
http://blog.chinaunix.net/uid-25132162-id-1641515.html