Bitwise operators and Their Applications

Source: Internet
Author: User
Tags bitwise operators
I. Six operators in C language:

& Bitwise AND

| By bit or

^ Bitwise OR

~ Invert

<Move left

> Right shift

 

1. bitwise AND OPERATION

Bitwise AND operator "&" are binary operators.

Its function is the binary phase corresponding to the two numbers involved in the operation. The result bit is 1 only when the two binary numbers are 1. Otherwise, the result bit is 0. The number of involved operations is supplemented.

For example, 9 & 5 can be written as follows: 00001001 (Binary complement of 9) & 00000101 (Binary complement of 5) 00000001 (Binary complement of 1) Visible 9 & 5 = 1.

Bitwise AND operations are usually used to clear some bits or retain some bits. For example, if a clears the high eight bits of 0 and retains the low eight bits, it can be used as a & 255 operation (255 of the binary number is 0000000011111111 ).

 

main(){int a=9,b=5,c;c=a&b;printf("a=%d\nb=%d\nc=%d\n",a,b,c);}

2. bitwise OR operation

The bitwise OR operator "|" is a binary operator.

Its function is the binary phase or corresponding to the two numbers involved in the operation. If one of the two binary numbers is 1, The result bit is 1. The two numbers involved in the operation appear as a complement.

Example: 9 | 5 writable formula: 00001001 | 00000101

00001101 (decimal 13) Visible 9 | 5 = 13

main(){int a=9,b=5,c;c=a|b;printf("a=%d\nb=%d\nc=%d\n",a,b,c);
3. bitwise exclusive or operation

The bitwise XOR operator "^" is a binary operator.

This function is used to calculate whether the binary numbers corresponding to the binary numbers are different or not. When the binary numbers of the two numbers are different, the result is 1. The number of involved operations still appears as a complement.

For example, 9 ^ 5 can be written as follows: 00001001 ^ 00000101 00001100 (12 in decimal format)

main(){int a=9;a=a^15;printf("a=%d\n",a);}

4. Inverse Calculation

Inverse Operator ~ It is a single object operator and has the right combination.

This function is used to reverse the binary numbers involved in the operation by bit.

Example ~ 9 is calculated as follows :~ (0000000000001001) Result: 1111111111110110

 

5. Left shift operation

The Left shift operator <is a binary operator. Shift n to the left is multiplied by the N power of 2.

Its function shifts the binary numbers on the left of "<" to several places left. The number on the right of "<" indicates the number of digits to be moved, Which is discarded at a high position and supplemented by 0 at a low position.

1) For example, a <4 refers to moving each binary of a four places to the left. For example, if a = 00000011 (decimal 3), after four digits are left removed, the value is 00110000 (decimal 48 ).

2) Example:

Int I = 1;

I = I <2; // shifts the value in I two places to the left.

That is to say, the binary system of 1 is 000... 0001 (here, the number of 0 in front of 1 is related to the number of digits in int, 32-bit machine, 31 0 in gcc), shifted to 000 after 2 digits left... 0100, that is, 4 in decimal system. Therefore, if the Left shift of 1 is equivalent to multiplying by 2, then the left shift of n is multiplied by the Npower of 2 (the number of symbols is not fully applicable, this is because the left shift may cause symbol changes. The reasons are described below)

Note the following:Int type, the leftmost sign bit and shift out. we know that int Is the signed integer number, and the first bit on the leftmost side is the signed bit, that is, 0 is positive and 1 is negative. Then, overflow occurs during the shift,

For example:

Int I = 0x40000000; // 40000000 of hexadecimal notation, 01000000 of hexadecimal notation... 0000

I = I <1;

Then, after I shifts 1 to the left, it will become 0x80000000, that is, 100000 of the binary system... 0000, the sign bit is set to 1, and the other bits are all 0, which is changed to the minimum value that can be expressed by the int type. The 32-bit int value is-2147483648, overflow. what will happen if I is moved 1 to the left? In C language, the highest bit is discarded. After 1 is discarded, the value of I is changed to 0.

A special case in the left shift is that when the number of digits in the left shift exceeds the maximum number of digits in the value type, the compiler will use the number of digits in the left shift to de-model the maximum number of digits and then shift by the remainder, for example:

Int I = 1, j = 0x80000000; // set int to 32 characters

I = I <33; // 33% 32 = 1 shifted to 1, and I changed to 2

J = j <33; // 33% 32 = 1 shifts 1 bit left, j changes to 0, and the highest bit is discarded.

When compiling this program with gcc, the compiler will provide a warning, indicating the number of places to move left> = type length. in fact, I, j moves the remainder of 1 bit, that is, 33% after 32. this rule is implemented in gcc. It is unclear whether other compilers are the same.

In short, the Left shift is: discard the highest bit, 0 fill the second bit

6. Right Shift operation

The right shift operator ">" is a binary operator. The N-digit shift to the right is divided by the n-th power of 2.

Its function is to shift all the binary numbers on the left of ">" to several places right, and the right of ">" to the specified number of digits.

For example, if a = 15, a> 2, 000001111 is shifted to 00000011 (decimal 3 ).

It should be noted that, for the number of signed characters, the symbol bit will be moved along with the right shift. When it is a positive number, the maximum bit is 0, while the negative number, the sign bit is 1, the maximum bit is 0 or fill 1 depends on the provisions of the compilation system. Turbo C and many systems require completing 1.

The processing of the right shift symbol is different from that of the left shift:

For signed integers, for example, int type, the right shift will keep the symbol bit unchanged. For example:

Int I = 0x80000000;

I = I> 1; // The I value will not change to 0x40000000, but 0xc0000000

That is to say, for the number of symbols, after the sign bit moves to the right, if the positive number is filled with 0, the negative number is supplemented with 1,

For the number of symbols, the symbol bit will be moved along with the right shift:

When the number is positive, the maximum bit is 0,

When it is a negative number, the symbol bit is 1,

That is, the right shift of arithmetic in assembly language. When the number of digits to be moved exceeds the length of the type, the remainder is obtained and then the remainder is moved.

The maximum bit is 0 or 1 depending on the requirements of the compilation system. Turbo C and many systems require completing 1.

Negative number 10100110> 5 (assuming the word length is 8 characters), the result is 11111101.

In short, in C, the Left shift is the logical/arithmetic left shift (the two are identical), and the right shift is the arithmetic right shift, which will keep the symbol bit unchanged. in practical applications, you can use the left/right shift to perform fast multiplication/Division operations, which is much more efficient than loop operations. x> 1; // equivalent to x/= 2x <1; // equivalent to x * = 2x> 2; // x/= 4x <2; // x * = 4x> 3; // x/= 8x <3; // x * = 8 and so on.

Unsigned:

main(){unsigned a,b;printf("input a number: ");scanf("%d",&a);b=a>>5;b=b&15;printf("a=%d\tb=%d\n",a,b);}

Let's look at another example!

main(){    char a='a',b='b';    int p,c,d;    p=a;    p=(p<<8)|b;    d=p&0xff;    c=(p&0xff00)>>8;    printf("a=%d\nb=%d\nc=%d\nd=%d\n",a,b,c,d);}

 

 

Ii. Advantages of different or operations

1. enable specific positioning to flipThe number of bits to be flipped can be set to 1 in sequence.

2 and 0, retain the original value.

3. Exchange two values without temporary variables.

We can exchange variable values without introducing other variables.

You can use an exclusive or operation:

A = a ^ B; // (1)
B = a ^ B; // (2)
A = a ^ B; // (3)

The XOR operation satisfies the combination law and exchange law, and is known by the nature of the XOR operation. For any integer a ^ a = 0;

Evidence: (a) a = a ^ B = (B in step (1) is substituted into B) a ^ (a ^ B) = B;

(B in step (3) B = a ^ B = (B in step (1) is substituted into B and a in step (2) is substituted into) a ^ B ^ a ^ B =;

 

3. bitwise AND OPERATION

1. Clear1 In number A, and 0 in B. Then perform an & Operation on the two to clear.

2. Take some locations in a numberTake some bits of number A, and set some bits of number B to 1.

3. retain one digitNumber A and number B perform the & operation. Number B is the bit 1 to be retained in number A, and the remaining bit is zero.

4. Judge parityReturns the parity of variable. Bitwise AND operation is performed on a and 1. If the result is 1, a is an odd number. bitwise AND operation is performed on a and 1. If the result is 0, a is an even number.

4. Application Example

1. Determine whether int variable A is an odd or even number.

A & 1 = 0 even
A & 1 = 1 odd

2. Take the K-bit of int-type variable

(K = 0, 1, 2 ...... Sizeof (int), that is, a> k & 1

3. Clear the K bit of int type variable A to 0, That is, a = &~ (1 <k)

4. Set the K position of int type variable A to 1, That is, a = a | (1 <k)

5. Int type variable loops move left K times, That is, a = a <k | a> 16-k (set sizeof (int) = 16)

6. Int type variable A shifts K times to the right, That is, a = a> k | a <16-k (set sizeof (int) = 16)

7. Average of Integers

If two integers x and y are used to calculate the average value (x + y)/2, the overflow will occur, because x + y may be greater than INT_MAX, but we know that their average value is definitely not enough for them? /DIV>

Int average (int x, int y) // returns the average value of X and Y.
{
Return (x & y) + (x ^ y)> 1 );
}

8. judge whether an integer is the power of 2. For a number x> = 0, determine whether it is the power of 2.

Boolean power2 (int x)
{
Return (x & (x-1) = 0) & (x! = 0 );
}

9 do not use temp to swap two integers
Void swap (int x, int y)
{
X ^ = y;
Y ^ = x;
X ^ = y;
}

Php:
$ A = 'dd ';
$ B = 'bb ';

$ A = $ a ^ $ B;
$ B = $ a ^ $ B;
$ A = $ a ^ $ B;
Echo $ a, '', $ B;

10 calculate the absolute value
Int abs (int x)
{
Int y;
Y = x> 31;
Return (x ^ y)-y; // or: (x + y) ^ y
}

11. Convert the modulo operation into a bitwise operation (without Overflow)
A % (2 ^ n) is equivalent to a & (2 ^ n-1)

12 multiplication is converted into bitwise operations (without Overflow)
A * (2 ^ n) is equivalent to a <n

13. Division operations are converted into bitwise operations (without Overflow)
A/(2 ^ n) is equivalent to a> n
For example: 12/8 = 12> 3

14. a % 2 is equivalent to a & 1 (a & log2 (2 ))
A % 4Equivalent to a & 2(A & log2 (4 ))

.....
A % 32 is equivalent to a & 5


15If (x = a) x = B;
Else x =;
It is equivalent to x = a ^ B ^ x;

The opposite number of 16 x is expressed (~ X + 1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.