Bit operation highlights

Source: Internet
Author: User

In this article, 2 'K represents the k power of 2

The k power of 1 divided by 2 can be computed using bits:

N/2 'K = n> K

The bitwise operation can be used to obtain the remainder of the K-power pair of 2:

N % 2 'K = N & (1 <k)-1)

For example, 100% 32

The binary value of 100 is 1100100.

(1 <5)-1) equal to 31 is 0011111

The two data phases get 100, so

100% 32 = 4

3 For integer N, from the low position, set its K-bit (0 <= k <= 31) to 1:

N = n | (1 <K)

4 For integer N, from the low position, set its K-bit (0 <= k <= 31) to 0:

N = N &~ (1 <K)

5 For integer N, from the low position, test whether its K-bit (0 <= k <= 31) is 1. If it is 1, return a number greater than 0, otherwise, 0 is returned.

Return N & (1 <K)

  

6. For integer N, determine whether it is an odd or even number.

If N & 1 is greater than 0, n is an odd number; otherwise, n is an even number.

  

7 For integer N, if n is an odd number, the N minus 1 is converted into an even number. If n is an even number, the N plus 1 is converted into an odd number.

N = n ^ 1

  

8 For an odd number of N, the following properties are available:

(N-1) ^ n = 1

  

9 maximum int

01 1111111111 1111111111 1111111111

Max_int = ~ (1 <31)

  

10 smallest int

10 0000000000 0000000000 0000000000

Min_int = (1 <31)

  

11. Change the value of 1 to 0.

For example: 111000 ---> 110000

N = N-(N &-N)

  

12. Determine whether two integers are of the same number.

# Define mask 0x80000000

Flag = (X & Mask) ^ (Y & Mask)

If the flag is 0, it indicates different numbers. Otherwise, the same number is used.

  

13. Exchange two values without temporary variables

 

To swap values of A and B, use the following value assignment statement:
A = A then B;
B = B then;
A = A then B;

14 bitset C language implementation

 

 

[Transfer] http://kenby.iteye.com/blog/1011480

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.