操作最右侧位

来源:互联网 发布:企业网络危机公关公司 编辑:程序博客网 时间:2024/04/27 21:53

#include <iostream>
#include <bitset>
#include <limits>
using namespace std;

#define out(T) cout<<bitset<numeric_limits<unsigned char>::digits>(T)<<endl<<endl

#define power(T, S) ((T)==0) ? cout<<"x"<<" is a power of 2"<<endl<<endl : cout<<"x"<<" is not a power of 2"<<endl<<endl
#define power_1(T, S) ((T)==0) ? cout<<"x"<<" is 2^n - 1"<<endl<<endl : cout<<"x"<<" is not 2^n - 1"<<endl<<endl
#define power_n_m(T, S) ((T)==0) ? cout<<"x"<<" is 2^n - 2^m"<<endl<<endl : cout<<"x"<<" is not 2^n - 2^m"<<endl<<endl

void  main() {
 unsigned char p = 0;
 unsigned char x = 0x58;
 // 0101 1000 -> 0101 0000    最右侧1位改为0位
 x = 0x58;   out(x);
 p = x & (x-1);  out(p);
 power(p & (unsigned char)(-1), x);    // 0检测 为 2 的幂
 


 // 0000 1111 -> 0000 0000    
 x = 0x0F;   out(x);
 p = x & (x+1);  out(p);   
 power_1(p & (unsigned char)(-1), x); // 0检测 为 2^n -1

 

 

 // 0101 1000 -> 0000 1000   // 析出最右侧的 1 位
 x = 0x58;   out(x);
 p = x & (-x);  out(p);
 // 1010 0111 -> 0000 1000   // 析出最右侧的 0 位
 x = 0xA7;   out(x);
 p = ~x & (x+1);  out(p);
 x = 0xFF;   out(x);
 p = ~x & (x+1);  out(p);

 

 

 // 0101 1000 -> 0000 0111   //构造识别后缀 0 的掩码
 x = 0x58;   out(x);  
 p = ~x & (x-1);  out(p);
 p = ~(x | -x);  out(p);
 p = (x & -x)-1;  out(p);

 

 

 // 0101 1000 -> 0000 1111   //构造识最右侧的1位和后缀0的掩码
 x = 0x58;   out(x);
 p = x ^ (x-1);  out(p);
 x = 0x00;   out(x);
 p = x ^ (x-1);  out(p);

 

 

 

 // 0101 1000 -> 0101 1111   //向右传播最右侧的1位
 x = 0x58;   out(x);
 p = x | (x-1);  out(p);
 x = 0x00;   out(x);
 p = x | (x-1);  out(p);

 

 

 // 0101 1000 -> 0100 0000   //最右侧连续的1位串改成0位串
 x = 0x58;   out(x);
 p = ((x | (x-1))+1) & x;
      out(p);   
 // 0001 1110 -> 0000 0000
 x = 0x1E;   out(x);
 p = ((x | (x-1))+1) & x;
      out(p);
 power_n_m(p & (unsigned char)(-1), x);

 

 

 // 1010 0111 -> 1010 1111   //最右侧的0位改成1位
 x = 0xA7;   out(x);
 p = x | (x+1);  out(p);
 x = 0xFF;   out(x);
 p = x | (x+1);  out(p);
}

原创粉丝点击