C/C ++ bit operation skills

Source: Internet
Author: User

Prerequisites
Everyone is familiar with bitwise operations. Basic bitwise operations include, or, non, XOR, and so on. During the interview, I often encountered bitwise operation-related questions, so I made a simple arrangement and referred to a lot of well-written blogs and books.

Now let's just briefly talk about the shift operation.

Left shift operation: x <y. Shift x to the left, discard y at the far left of x, and add y 0 at the right.

Right Shift operation: x> y. Shifts x to the right of y, which indicates whether x is a signed number or an unsigned number. When x is an unsigned number, you only need to discard the rightmost y bits of x and add y 0 to the left. When x is a signed number, x is also divided into positive or negative numbers. If the number is positive, it is the same as that of the unsigned number. If the number is negative, the rightmost y bit of x is discarded and the y 1 is added to the left.

 


Bit operation skills
Calculate the number of 1 in the binary of a number
By performing operations with the flag bit whose initial value is 1, you can determine whether the second bit is 1. Then, you can move the flag bit left to determine whether the second low position is 1, the result is that each digit is determined.


[Cpp]
/*
Calculate the number of 1 in the binary of a number
*/
Int countOf1 (int num)
{
Int count = 0;
Unsigned int flag = 1;
 
While (flag)
{
If (num & flag)
{
Count ++;
}
 
Flag = flag <1;
}
Return count;
}

/*
Calculate the number of 1 in the binary of a number
*/
Int countOf1 (int num)
{
Int count = 0;
Unsigned int flag = 1;

While (flag)
{
If (num & flag)
{
Count ++;
}

Flag = flag <1;
}
Return count;
}
Another method is to subtract one from an integer, so that the rightmost 1 of the integer is 0, and the right 0 of this 1 is 1. Perform and calculate the subtraction of the integer and integer, and change the rightmost 1 of the integer to 0, and the remaining digits remain unchanged. Until the value of this integer is 0, the number of operations and operations is the number of 1 in the integer.


[Cpp]
/*
Calculate the number of 1 in the binary of a number
*/
Int countOf1_2 (int num)
{
Int count = 0;
 
While (num)
{
Num = num & (num-1 );
Count ++;
}
Return count;
}

/*
Calculate the number of 1 in the binary of a number
*/
Int countOf1_2 (int num)
{
Int count = 0;

While (num)
{
Num = num & (num-1 );
Count ++;
}
Return count;
}

 


Determine whether a number is the N power of 2
If a number is the N power of 2, the highest bit of this number is 1, and the rest is 0. The solution can be easily obtained based on the second solution in the previous question. Subtract one of the integers from each other and perform operations. If the result is zero, it can be proved that the number is 2 to the Npower.


[Cpp]
/*
Determine whether a number is the N power of 2 (a number is the N power of 2, then the highest bit is 1, and the remaining bit is 0)
*/
Bool is2Power (int num)
{
Bool flag = true;
 
Num = num & (num-1); // calculates the sum of num and num-1
If (num) // if the result is 0, it is not the Npower of 2
{
Flag = false;
}

Return flag;
}

/*
Determine whether a number is the N power of 2 (a number is the N power of 2, then the highest bit is 1, and the remaining bit is 0)
*/
Bool is2Power (int num)
{
Bool flag = true;

Num = num & (num-1); // calculates the sum of num and num-1
If (num) // if the result is 0, it is not the Npower of 2
{
Flag = false;
}
 
Return flag;
}

 

Steps after integer n can be changed to integer m
The variance or result of n and m can tell the number of two different bits, and then call the method to calculate the number of 1 in a number to obtain the result.


[Cpp]
/*
The number of operation steps required when n is changed to m
*/
Int countChange (int n, int m)
{
N = n ^ m; // calculate the variance or between n and m, and then calculate the number of 1 in the result.
Return countOf1_2 (n );
}

/*
The number of operation steps required when n is changed to m
*/
Int countChange (int n, int m)
{
N = n ^ m; // calculate the variance or between n and m, and then calculate the number of 1 in the result.
Return countOf1_2 (n );
}

 

Obtain the maximum int value.

[Cpp]
/*
Obtain the maximum int value.
Expected result: 2147483647
*/
Int getMaxInt ()
{
Return (1 <31)-1;
}
 
/*
Compiled using g ++, the following error occurs: warning: left shift count is negative
*/
Int getMaxInt_2 ()
{
Return (1 <-1)-1;
}
 
Int getMaxInt_3 ()
{
Return ~ (1 <31 );
}
 
/*
If you do not know the length of the int, use
*/
Int getMaxInt_4 ()
{
Return (unsigned int)-1)> 1;
}

/*
Obtain the maximum int value.
Expected result: 2147483647
*/
Int getMaxInt ()
{
Return (1 <31)-1;
}

/*
Compiled using g ++, the following error occurs: warning: left shift count is negative
*/
Int getMaxInt_2 ()
{
Return (1 <-1)-1;
}

Int getMaxInt_3 ()
{
Return ~ (1 <31 );
}

/*
If you do not know the length of the int, use
*/
Int getMaxInt_4 ()
{
Return (unsigned int)-1)> 1;
}

 

Obtain the minimum int value.
Similar to getting the maximum int value.


[Cpp]
/*
Minimum int
Expected result:-2147483648.
*/
Int getMinInt ()
{
Return 1 <31;
}
 
/*
Compiled in g ++, the following error occurs: warning: left shift count is negative.
*/
Int getMinInt_2 ()
{
Return 1 <-1;
}

/*
Minimum int
Expected result:-2147483648.
*/
Int getMinInt ()
{
Return 1 <31;
}

/*
Compiled in g ++, the following error occurs: warning: left shift count is negative.
*/
Int getMinInt_2 ()
{
Return 1 <-1;
}


Obtain the largest long

[Cpp]
/*
Max long
Expected result: 9223372036854775807
*/
Long getMaxLong ()
{
Return (unsigned long)-1)> 1;
}

/*
Max long
Expected result: 9223372036854775807
*/
Long getMaxLong ()
{
Return (unsigned long)-1)> 1;
}

 

Judge the parity of a number
Judging parity is actually determining whether the last digit is 1.


[Cpp]
/*
Returns 1, which is an odd number. returns 0, which is an even number.
*/
Bool isOdd (int num)
{
Return num & 1 = 1;
}

/*
Returns 1, which is an odd number. returns 0, which is an even number.
*/
Bool isOdd (int num)
{
Return num & 1 = 1;
}

 

Swap two numbers (with no third variable)
There are also several methods to exchange two numbers without the third variable, such as a = a + B; B = a-B; a = a-B. The following method can be implemented based on the difference or between a number m and another number n, and then returns m.


[Cpp]
/*
Temporary variables are not applicable. Two numbers are exchanged.
A = a ^ B
B = B ^
A = a ^ B
*/
Void mySwap (int * a, int * B)
{
(* A) ^ = (* B) ^ = (* a) ^ = (* B );
}

/*
Temporary variables are not applicable. Two numbers are exchanged.
A = a ^ B
B = B ^
A = a ^ B
*/
Void mySwap (int * a, int * B)
{
(* A) ^ = (* B) ^ = (* a) ^ = (* B );
}

 

Returns the absolute value of a number.
The basic implementation of the following method is to shift n 31 places to the right and obtain the n symbol.


[Cpp]
/*
Take absolute value
N shifts 31 places to the right to obtain the n symbol. If n is a positive number, 0 is obtained. If n is a negative number,-1 is obtained.

*/
Int myAbs (int n ){
Return (n ^ n> 31)-(n> 31 );
}

/*
Take absolute value
N shifts 31 places to the right to obtain the n symbol. If n is a positive number, 0 is obtained. If n is a negative number,-1 is obtained.
 
*/
Int myAbs (int n ){
Return (n ^ n> 31)-(n> 31 );
}

 

Calculate the average value of two numbers
The first method is more common and simple. In the second method, we need to know that (m ^ n)> 1 produces half of the values of 1 in the number of m and n, the result obtained by m & n is the bits where m and n are both 1. The two results are added to obtain the mean of m and n.


[Cpp]
/*
Returns the mean of m and n.
*/
Int getAverage (int m, int n ){
Return (m + n)> 1;
}
 
/*
Returns the mean of m and n.
(M ^ n)> 1-> obtain the number of some bits of m and n as half of 1.
M & n-> obtain some bits whose values are 1 in m and n.
*/
Int getAverage_2 (int m, int n ){
Return (m ^ n)> 1) + (m & n );
}

/*
Returns the mean of m and n.
*/
Int getAverage (int m, int n ){
Return (m + n)> 1;
}

/*
Returns the mean of m and n.
(M ^ n)> 1-> obtain the number of some bits of m and n as half of 1.
M & n-> obtain some bits whose values are 1 in m and n.
*/
Int getAverage_2 (int m, int n ){
Return (m ^ n)> 1) + (m & n );
}

 

Solve m-bit reciprocal Problems

[Cpp]
/*
Obtain the m-th digit of n (counted from 1)
*/
Int getMthByTail (int n, int m ){
Return (n> (m-1) & 1;
}
 
/*
Set the m-th digit of n to 1.
*/
Int setMthByTail21 (int n, int m)
{
Return n | (1 <(m-1 ));
}
 
/*
Set the m-th digit of n to 0.
*/
Int setMthByTail20 (int n, int m)
{
Return n &~ (1 <(m-1 ));
}

/*
Obtain the m-th digit of n (counted from 1)
*/
Int getMthByTail (int n, int m ){
Return (n> (m-1) & 1;
}

/*
Set the m-th digit of n to 1.
*/
Int setMthByTail21 (int n, int m)
{
Return n | (1 <(m-1 ));
}

/*
Set the m-th digit of n to 0.
*/
Int setMthByTail20 (int n, int m)
{
Return n &~ (1 <(m-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.