char类型的位操作

 

getbit  判断一个char型变量的任意比特位是否为1

setbit  设置char型变量的任意比特位 true 为1 false 为0

#define CHAR_0 128 #define CHAR_1 64 #define CHAR_2 32 #define CHAR_3 16 #define CHAR_4 8 #define CHAR_5 4 #define CHAR_6 2 #define CHAR_7 1 #define CHAR_GETBIT(c,i) ((CHAR_##i&c)!=0) #define CHAR_SETBIT(cp,i,v) if (v)/ {/ *cp|=CHAR_##i;/ }/ else/ *cp^=CHAR_##i; bool getbit(char c, int i) { switch(i) { case 0: return CHAR_GETBIT(c,0); case 1: return CHAR_GETBIT(c,1); case 2: return CHAR_GETBIT(c,2); case 3: return CHAR_GETBIT(c,3); case 4: return CHAR_GETBIT(c,4); case 5: return CHAR_GETBIT(c,5); case 6: return CHAR_GETBIT(c,6); case 7: return CHAR_GETBIT(c,7); default: cout<<"[getbit] the index is error "; exit(0); } } void setbit(unsigned char* cp, int i, bool v) { switch(i) { case 0: CHAR_SETBIT(cp,0, v); return; case 1: CHAR_SETBIT(cp,1, v); return; case 2: CHAR_SETBIT(cp,2, v); return; case 3: CHAR_SETBIT(cp,3, v); return; case 4: CHAR_SETBIT(cp,4, v); return; case 5: CHAR_SETBIT(cp,5, v); return; case 6: CHAR_SETBIT(cp,6, v); return; case 7: CHAR_SETBIT(cp,7, v); return; default: cout<<"[setbit] the index is error "; exit(0); } } 

 

你可能感兴趣的:(编程技巧,c)