Bitwise Programming

1. Checking whether K-th bit is set or notLet us assume that given number is n. Then for checking the K-th bit, use the following expression:n & (1 << K -1).If the expression is true then we can say the k-th bit is set(that means , set to 1)Example: n = 01001011 And K = 4n & (1 << k-1) 000010002. Setting K-th bitFor a given number n , to set the K-th, use the following expression:n | 1 << (K-1).Example: n = 01001011 And K = 3n | (1 << K-1) 010011113. Clearing K-th bitTo clear K-th bit of a given number n, use the following expression:n & ~ (1 << K -1).Example: n = 01001011 And K = 4n & ~(1 << K – 1) 010000114. Toggling K-th bitFor a given number n, for toggling the K-th bit, use the expression:n ^ (1 << K -1).Example: n = 01001011 And K = 31 << (K – 1) 00000100

n ^ (1 << K -1) 010011115. Checking whether number is Power of 2 or notGiven number n, to check whether the number is 2 raised to power n form or not, use the following expression:if (n & n-1 == 0).Example: n = 01001011n – 1 = 01001010

n & n-1 = 01001010

if(n & n-1 == 0) 06. Multiplying number by power of 2For a given number n, to multiply the number with 2 raised to power K, use the following expression:n << K.Example: n = 01001011 and K = 2n << K 001011007. Dividing number by power of 2For a given number n, to divide the number with 2 raised to power K, use the following expression:n >> k.Example: n = 01001011 And K = 2n >> K 000100108. Finding Modulo of a Given NumberFor a given number n, to find the %8, use the following expression:n & 0x7. Similarly, to find %32, use the following expression:n & 0x1F.Important note: As stated above, we can write for any modulo value.9. Average without DivisionIs there a bit-twiddling algorithm to replace mid = (low + high) / 2 (used in Binary Search and Merge Sort) with something much faster?Usemid = (low + high) >> 1, But, by using this there may be the possibility o f integer overflow, to overcame this issue , use the following expression:low + ((high – low) >>1).Wiki PageBlog Page

News Reporter

Leave a Reply

Your email address will not be published. Required fields are marked *