您的位置:首页 > 其它

实现一个对8bit数据指定某一位置0或1

2015-06-08 23:24 288 查看
<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 0011else{*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 0011else 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;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: