当前位置:网站首页>8. C language - bit operator and displacement operator

8. C language - bit operator and displacement operator

2022-07-06 13:26:00 It's Wang Jiujiu

This paper adopts 《C Primer Plus》、《C Traps and defects 》 And the teaching video of bit technology .

Yes C Language bit operators and displacement operators are explained in detail , To impress , Each knowledge point has examples and practical explanations

Catalog

Bit operators

1. Press ( Binary system ) Bit and  &

2. Press ( Binary system ) Bit or   |

3. Press ( Binary system ) Bit exclusive or   ^

4. Press ( Binary system ) Bit inversion :~

Bit operator usage

1. Mask

2. Open bit ( Set bit )

3. Off bit ( Clear the vacancy )

The displacement operator

1. Shift left operator

2. Shift right operator

Displacement operator usage

1. Use the displacement operator to convert integers into binary form

2. After converting a value n position


Bit operators

1. Press ( Binary system ) Bit and  &

The rules : The corresponding bits are 1 when , The result is 1, Otherwise 0.

for example :

int a = 1,b = 3;

00000000 00000000 00000000 00000001  //a

00000000 00000000 00000000 00000011  //b

00000000 00000000 00000000 00000001  //a&b=1

When the value is stored in the computer , Are stored in the form of complement , Positive integer ( Include 0) The original code of 、 Inverse code 、 The complement is the same ; And the original code of negative numbers 、 Inverse code 、 The complement needs to be calculated : By inverting the original code and adding 1, You can get the complement of an integer ; Similarly, add a complement inversely 1, You can also get the original code of this number .

#include<stdio.h>
int main()
{
	int a = 1;
	int b = 3;
	int c = a & b;
	printf("a=%d,b=%d,c=%d\n", a, b,c);
	return 0;
}

2. Press ( Binary system ) Bit or   |

The rules : As long as one of the corresponding bits is 1, The results for 1, Otherwise 0.

for example :

int a = 1,b = 3;

00000000 00000000 00000000 00000001  //a

00000000 00000000 00000000 00000011  //b

00000000 00000000 00000000 00000011  //a|b=3

#include<stdio.h>
int main()
{
	int a = 1;
	int b = 3;
	int c = a | b;
	printf("a=%d,b=%d,c=%d\n", a, b,c);
	return 0;
}

3. Press ( Binary system ) Bit exclusive or   ^

The rules : Only one corresponding bit is 1, The result is 1, Otherwise 0.

for example :

int a = 1,b = 3;

00000000 00000000 00000000 00000001  //a

00000000 00000000 00000000 00000011  //b

00000000 00000000 00000000 00000010  //a^b=2

#include<stdio.h>
int main()
{
	int a = 1;
	int b = 3;
	int c = a ^ b;
	printf("a=%d,b=%d,c=%d\n", a, b,c);
	return 0;
}

  practice : Use the XOR operator to exchange the values of two variables ( No extra variables are created )

#include<stdio.h>
int main()
{
	int a = 1;
	int b = 3;
	printf("a=%d,b=%d\n", a, b);
	a = a ^ b;//2
	printf("1:a=%d,b=%d\n", a, b);
	b = a ^ b;//1
	printf("2:a=%d,b=%d\n", a, b);
	a = a ^ b;//3
	printf("3:a=%d,b=%d\n", a, b);
	return 0;
}

4. Press ( Binary system ) Bit inversion :~

hypothesis a The type is int,a To be an assignment 1;

a:

Original code :00000000 00000000 00000000 00000001

Inverse code :00000000 00000000 00000000 00000001   

Complement code :00000000 00000000 00000000 00000001   

Reverse it by bit , Turned out to be 0 The place becomes 1, Turned out to be 1 The place becomes 0, Then after taking the opposite, it becomes :

~a:

Complement code :11111111  11111111   11111111  11111110

Inverse code :10000000 00000000 00000000 00000001   // The sign bits remain the same , Other bits are reversed

Original code :10000000 00000000 00000000 00000010  // Inverse code +1,~a = -2

#include<stdio.h>
int main()
{
	int a = 1;
    int b = ~a;
	printf("a=%d b=%d \n", a,b);
	return 0;
}

  notes : The bit operation itself does not change the value of the variable , Instead, create a new value , If you want to change the value of a variable, you can use :&=、|=、^=、~=.

Bit operator usage

1. Mask

Bitwise and operators are often used with masks (mask). The so-called mask refers to some set to on (1) Or off (0) Bit combination of .

Define a symbolic constant MASK by 2, The form of the next eight bits in memory is 00000010, This MASK Scale mask .

Define another variable a, The assignment is 7, The form of the next eight bits in memory is 00000111.

#include<stdio.h>
#define MASK 2
int main()
{
	int a = 7;
	a &= MASK;
	printf("a=%d\n", a);//a=2
	return 0;
}

a&MASK = 00000010, On the far right is 0 No. A , Leftmost 7 No. A . In the process of bitwise AND , except 1 Number one 1 Shows , All remaining bits are displayed as 0. This process is called “ Use a mask ”, Because in the mask 0 Hidden variables a The corresponding bit in . Here are the common uses of bitwise AND :

a &= 0xff;
// perhaps 
a &= 0377;

0xff by 16 Base number , Its binary form is 11111111, The octal form is 0377. This mask will hold variables a The last eight digits in the remain unchanged , The other bits are set to 0. No matter what a How many people are there , The final values are modified to 1 individual 8 Bit byte ,8 Is the width of the mask .

2. Open bit ( Set bit )

Sometimes it is necessary to open a specific position in a value , While keeping the other bits unchanged . for example : To turn on the built-in speakers , Must open 1 No. A , While keeping the other bits unchanged , In this case, you can use bitwise OR operator (|).

Set a variable a and MASK( Only position one is 1) For example :

hypothesis a by 00000111,MASK by 00000010, that a |= MASK =00000111.

MASK In Chinese, it means 1 Bit ,a Also in 1;MASK In Chinese, it means 0 Bit ,a Keep the same in .

If you want to open it at the same time 1、3、5 No. A , Then you can put MASK Set to :00101010, Set according to different needs MASK.

3. Off bit ( Clear the vacancy )

Similar to the open bit , Sometimes it is also necessary to turn off finger positioning without affecting other bits . Suppose you want to close the variable a Medium 1 No. A , You can do this :

Define symbolic constants MASK Only 1 The number is 1:00000010

#include<stdio.h>
#define MASK 2
int main()
{
	int a = 6;
	printf(" Before change :%d\n", a);
	a &= ~MASK;
	printf(" After change :%d\n",a);
	return 0;
}

6 After binary 8 Position as :00000110

4 After binary 8 Position as :00000100

MASK In Chinese, it means 1 The bit of is cleared to 0, The other bits remain unchanged in the result .

The displacement operator

The operand of the displacement operator can only be an integer .

1. Shift left operator

The rules : Left abandon , Zero on the right .

for example :

int a = 5; stay C In language , Positive integer ( Include 0) The original code of 、 Inverse code 、 The complement is the same , As shown below :

a:

Original code :00000000 00000000 00000000 00000101

Inverse code :00000000 00000000 00000000 00000101   

Complement code :00000000 00000000 00000000 00000101   

a  << 1:

Complement code :0 00000000 00000000 00000000 000001010   

Fill one on the right 0, The leftmost 0 abandon ,a << 1 As the result of the 10.

#include<stdio.h>
int main()
{
	int a = 1;
	int a2 = a << 1;
	printf("a=%d,a2=%d\n", a, a2);
	int b = 5;
	int b2 = b << 1;
	printf("b=%d,b2=%d\n", b, b2);
	return 0;
}

Found by test :

  • The shift left operator can achieve *2 The effect of , The left one , The number *2; Move two places to the left , The number *4, And so on .
  • The displacement operator does not change the original value , Instead, it creates a new value that can be used or assigned .

2. Shift right operator

The rules : The right shift operator is divided into two rules: logical shift and digital shift .

Logical displacement : Left complement 0, On the right, abandon .

Arithmetic displacement : The sign bit of the left complement value , On the right, abandon .

Arithmetic displacement can ensure that the new value has the same sign as the original value , More scientific than logical displacement , Most compilers adopt this rule .

for example :

int a = -5;

Original code :10000000 00000000 00000000 00000101

Inverse code :11111111  11111111   11111111  11111010    // The sign bits remain the same , Other bits are reversed

Complement code :11111111  11111111   11111111  11111011    // Inverse code +1 Get the complement

a >> 1:

Complement code :11111111   11111111   11111111    11111101 // The sign bit of the left complement value 1, On the right, abandon 1

Inverse code :10000000  00000000  00000000  00000010

Original code :10000000  00000000  00000000  00000011   //a>>1 = -3

#include<stdio.h>
int main()
{
	int a = 1;
	int a2 = a >> 1;
	printf("a=%d,a2=%d\n", a, a2);
	int b = -5;
	int b2 = b >> 1;
	printf("b=%d,b2=%d\n", b, b2);
	return 0;
}

notes : For the displacement operator , Only moving positive integer digits is meaningful ! Move negative numbers 、 Decimals, etc. are undefined by the standard , Meaningless .

Displacement operator usage

1. Use the displacement operator to convert integers into binary form

#include<stdio.h>
#include<limits.h>

void itobs(int n, char* ps);// Compute binary 
void print_bstr(const char* str);// Print binary 

int main()
{
	printf(" Please enter a number  or  Press any other key to exit \n");
	int number = 0;
	char bin_str[CHAR_BIT * sizeof(int) + 1]={0};
	//CHAR_BIT Express char The number in , The return value is 8
	//8 * sizeof(int) Is the number of digits in an integer , You also need to leave a place for the terminator , Again +1
	while (scanf("%d", &number) == 1)// Jump out of the loop when entering illegal characters 
	{
		itobs(number, bin_str);// Compute binary 
		printf("%d The binary sequence of is :>", number);
		print_bstr(bin_str);// Print binary 
		putchar('\n');
	}
	return 0;
}

// Compute binary 
void itobs(int n, char* ps)
{
	int i = 0;
	const static int size = CHAR_BIT * sizeof(int);
	for (i = size - 1; i >= 0; i--, n >>= 1)
	{
		*(ps + i) = (01 & n) + '0';
		// In order to fit the computer better , use 01&n,01 by 8 Hexadecimal sequence form ,1&n Yes ,
		// Because the form of array is char type , In order to express 0 or 1, You also need to add characters 0 Value 
	}
	*(ps + size) = '\0';// The last position is assigned with a terminator 
}

// Print binary sequence 
void print_bstr(const char* str)
{
	int i = 0;
	while (*(str + i))// It's not an empty character 
	{
		putchar(*(str + i));
		if (++i % 8 == 0)// For viewing purposes , Every time 8 One space 
			putchar(' ');
	}
}
  • In the above code , CHAR_BIT It's a header file <limits.h> Macro definition in , This macro represents char The number in , The return value is 8.
  • expression sizeof(int) Find the size of an integer , The result is 4 Bytes ; expression CHAR_BIT * sizeof(int) Represents the number of digits of an integer .
  • function itobs Medium for The cycle starts from the last bit , Calculate the binary result , At the end of each cycle ,n>>1 Moves to the right one , Perform the previous calculation .
  • Formula 01&n There are only two results :0 or 1, In order to carry on char The array of type shows 0、1, You also need to add characters to the calculation result 0 Size (‘0’).
  • All operations in functions are in the form of pointers , So there is no need to return a value .

The final result is as follows :

2. After converting a value n position

Bitwise negation operator can switch all bits of a value , But the selected special location cannot be switched . Suppose you want to switch the last four digits of a value , How to do it? ?

You can use bitwise XOR (^) Finish the task , First create a mask , Then set the last four bits of the mask to 1, XOR the value you want to change with the mask , You can switch the last four digits of the value .

int invert(int num, int bits)
{
	int mask = 0;
	int val = 1;
	while (bits-- > 0)
	{
		mask |= val;
		val <<= 1;
	}
	return num ^= mask;
}
  • In the above formula , use num Receive the value you want to change , use bits Receive the number of digits you want to change .
  • mask For the mask ,val Set to 1, take mask And val Do or wait (|=), Can be mask The last digit is changed to 1, And then val One unit to the left , Cycle again , change mask The penultimate value , And so on , Until the end of the cycle .
  • hypothesis bits=4, So jump out while After the cycle ,mask The value stored on the computer is 000011111( Last eight ), With the num To engage in exclusive or , You can switch num The last four values .

Put this function in the conversion binary example , The operation results are as follows :

  Through observation, we found that , The XOR operation reverses the values of the last four digits .

原网站

版权声明
本文为[It's Wang Jiujiu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060916176226.html