当前位置:网站首页>Operation on a bit of binary

Operation on a bit of binary

2022-06-23 07:26:00 Pick up the famous Rose


Preface

Today I will explain to you how to process a bit of binary 1 Or clear 0.
This chapter requires the use of the in place operator & and |.
If you don't understand, you can move to C Language – Operator details
 Insert picture description here
The circled ones are the ones to be used in this section


One 、 Analysis steps

 Insert picture description here

Two 、 Use steps

1. Import and stock in

1. Set up 1

#define SETBIT(x,n) (x|=1<<(n-1))
void ShowBits(int x) {
    
	int num = sizeof(x) * 8 - 1;// Minus one is because binary has 32 position   The range of movement is 0~31 position 
	while (num >= 0)
	{
    
		if (x&1<<(num))
		{
    
			printf("1");
		}
		else
		{
    
			printf("0");
		}
		num--;
	}
	printf("\n");
}
int main() {
    
	int x = 0;
	SETBIT(x,5);// Place the fifth position 1
	ShowBits(x);// Print every bit of binary 
	return 0;
}

2. Set up 0

#define CLRBIT(x,n) (x&=(~(1<<(n-1))))
void ShowBits(int x) {
    
	int num = sizeof(x) * 8 - 1;// Minus one is because binary has 32 position   The range of movement is 0~31 position 
	while (num >= 0)
	{
    
		if (x&1<<(num))
		{
    
			printf("1");
		}
		else
		{
    
			printf("0");
		}
		num--;
	}
	printf("\n");
}
int main() {
    
	int x = 100;
	CLRBIT(x, 6);// Zero the sixth position 
	ShowBits(x);// Print every bit of binary 
	return 0;
}

2. Read in the data

 Insert picture description here
 Insert picture description here


原网站

版权声明
本文为[Pick up the famous Rose]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230621281411.html