實現一個對8bit資料指定某一位置0或1
阿新 • • 發佈:2019-02-06
<pre name="code" class="cpp">
方法一
#include<stdio.h> #include<math.h> void bit_set(unsigned char *p_date, unsigned char position, int flag) { char a =(char) pow(2, (position - 1)); //指數 2^(position - 1) if (flag == 1) { *p_date |= a;//0000 0010或0000 0001 |表示按位或 } // 0000 0011 else { *p_date &= ~a; //0000 0010&1111 1110 ~表示按位取反 } // 0000 0010 &表示按位與 } int main() { unsigned char val = 2; bit_set(&val, 1, 0); printf("%d\n", val); getchar(); return 0; }
方法二
#include<stdio.h> void bit_set(unsigned char *p_date, unsigned char position, int flag) { if (flag == 1) { *p_date |= (1 << (position - 1));//0000 0010或0000 0001 } // 0000 0011 else if (flag = 0) { *p_date &= ~(1 << (position - 1));//0000 0010&1111 1110 } // 0000 0010 } int main() { unsigned char val = 2; bit_set(&val, 1, 0); printf("%d\n", val); getchar(); return 0; }