[Interesting between C language and bit manipulation]

Interesting facts between C language and bit manipulation

Recently, in the process of learning single-chip microcomputer and ARM bare metal, it is found that bit operation is used very frequently, and bit operation is an indispensable role when operating registers. Looking back on the previous c language learning process, it seems that the bit operation only stays in a simple understanding of the concept, and I don't know how to use it. Let's talk about common bit operations.

一、认清位操作符号

在进行位操作的同时我们必须要搞清楚下面符号的区别
1. && and  &
2. || and  |
3.  ! and  ~
&& 表示逻辑与 & 表示位与 
||表示逻辑或  | 表示位或
!表示逻辑取反  ~表示位取反
对位操作时每个符号实际是对二进制数之间的操做

二、简单位操作使用

------------------------------例子演示---------------------------

#include <stdio.h>

int main(void)
{
    
    
	int a = 1,b = 2;
	int res1 = 0,res2 = 0,res3 = 0;
	int res4 = 0,res5 = 0,res6 = 0;
	res1  = a && b;
	res2 = a  & b;
	
	printf("res1 = %d  res2 = %d\n",res1,res2);
	//res1 = 1  res2 = 0
	res3 = a || b;
	res4 = a |  b;
	printf("res3 = %d  res4 = %d\n",res3,res4);
	//res3 = 1  res4 = 3
	
	res5 = !a;
	res6 = ~a  ;
	printf("res5 = %d  res6 = %d\n",res5,res6);
	//res5 = 0  res6 = -2
	return 0;
}

insert image description here

----------------------------------结果分析-----------------------------
1、 res1  = a && b;   -》逻辑与操作
 如果两个数都不为0相与则结果为1 如果有一个数为0则结果为0
2、res1  = a & b;    -》位与操作 先将其装换为二进制数然后从每位二进制相对应进行与操作
a = 1    ---> 0001  b = 2 ---> 0010
    0001
    0010
结果	0000 -0

3、res1  = a || b; -》逻辑与操作 只要有一个数不为0则结果为1 如果都为0则结果为0
4、res1  = a | b;  -》位与操作 先将其装换为二进制数然后从每位二进制相对应进行与操作
a = 1    ---> 0001  b = 2 ---> 0010
    0001
    0010
结果	0011 -3

5、res5 = !a;  -》逻辑取法 非0取反为00取反为1   -》结果0
6、res6 = ~ a; -》位取反 先将其装换为二进制 然后0110

位操作总结
1、位或特点:任意数与1位或为10位或无变化
2、位与特点:任意数与1位与无变化 与0位与为0
3、取反特点:原来位上为1变为00变为1

三、左移( << )与右移 ( >> )

The shift in c language depends on the data type - "left shift of unsigned number is zero padding on the right side. Right shift is left zero padding. Left shift of signed number is to fill zero on the right side (arithmetic shift), when right shift, the left side fills the sign bit (positive number complements 0, negative number complements 1)

四、位运算综合运用

设置时相应位置1 清除时相应位置0

1、设置bit3,其余位保持不变: a = a | (1 << 3);
2、清除a的bit5,其余位保持不变: a = a & (~(1 << 5));
3、清除bit15~bit23其余位保持不变: a = a & (~(0x1ff << 15);
4、取出a的bit3~bit8
思路:先将这个数bit3~bit8不变其余位清零、在将其右移3位
a = a & (0x3f << 3)
a = a >> 3;

5、用c语言给一个寄存器Bit7~bit17赋值937(其余位不受影响)
思路:先将bit7~bit17全部清零、将973写入Bit7~bit17
a = a & (~(0x7ff << 7);
a = a | (937 << 7);

6、给一个寄存器bit7~bit17中的值加上17
思路:先读出原来bit7~bit17、给这个数加17 、bit7~bit17清零、将第二步算出的值写入bit7~bit17
(这里定义一个临时变量unsigned int tmp = 0;)
unsigned int tmp = 0;
tmp = a & (0x3ff << 7);
tmp = tmp >> 7;
tmp += 17;
a = a & (0x3ff << 7);
a = a | (tmp << 7);

五、宏定义实现位操作
insert image description here

The above is a simple sharing of the alignment operation.

Guess you like

Origin blog.csdn.net/boybs/article/details/122971080