C language: bit operation ---- set a certain position to 1 or 0

C language basic development ---- directory


Preparation

To set a bit to 1 or 0 requires bit manipulation.

This time you need to use the four bit operations of AND (&), or (|), left shift (<<) and right shift (>>) .

Specific bit operation instructions: C language: bit operators ---- and (&), or (|), not (~), exclusive or (^), left shift (<<) and right shift (>>)

A certain bit - set to 1

Or (|) characteristics : 1 is 1, double 0 is 0.
1 or (|) any number is 1, which can realize the position 1 operation .
Any number of 0 or (|) can be any number, and when the position 1 operation can be realized, other bits will not be affected.
Then use the left shift and right shift operations to realize the setting operation of any bit.

The specific code is as follows:

#include <stdio.h>

int main(int argc, char *argv[])
{
    
    
	int m = 0x93;	//0x93 二进制: 1001 0011
	int a = m|(1<<3); //0x9b 二进制:1001 1011 
	 
	printf("a=0x%x\n",a);
	return 0;
}

The result of the operation is as follows:

insert image description here

A certain bit - set to 0

And (&) characteristics : 0 is 0, double 1 is 1. Any number of
0 and (&) is 0, which can realize the position 0 operation .
Any number of 1 and (&) can be any number, and when the operation of position 0 can be realized, other bits will not be affected.
Then use the left shift and right shift operations to realize the zero-setting operation of any bit.

The specific code is as follows:

#include <stdio.h>

int main(int argc, char *argv[])
{
    
    
	int m = 0x93;	//0x93 二进制: 1001 0011
 	int a = m&(~(1<<4)); //0x83 二进制:1000 0011 
 	
	printf("a=0x%x\n",a);
	return 0;
}

The result of the operation is as follows:
insert image description here


Guess you like

Origin blog.csdn.net/MQ0522/article/details/129717618