Category: Binary

Compute parity of a number using lookup table

Given an integer, calculate its Parity. The parity refers to the number of 1’s in a given binary number.   Odd parity (encoded as 1) means there are an odd number of 1’s and even parity (encoded as 0) means that there are an even number of 1’s. Parity bits are often used as a …

Bit Hacks – Part 6 (Random Problems)

In this post, we will discuss few unrelated problems that can be solved using bit manipulation hacks.   Below Problems are covered in this post – Problem 1. Find number of bits needed to be flipped to convert given integer to another Problem 2. Conditionally negate a value without branching Problem 3. Find XOR of …

Bit Hacks – Part 4 (Playing with letters of English alphabet)

In this post we will discuss some of the bit hacks/tricks on letters of English alphabet.   Below tricks are covered in this post – Trick 1. Convert uppercase character to lowercase Trick 2. Convert lowercase character to uppercase Trick 3. Invert alphabet’s case Trick 4. Find letter’s position in alphabet     Trick 1. …

Bit Hacks – Part 3 (Playing with rightmost set bit of a number)

In this post we will discuss few related problems that are related to unsetting the rightmost set bit of a number.   How to unset the rightmost set bit of a number? The expression (n & (n – 1)) will turn off the rightmost set bit of given number. (n – 1) will have all …

Bit Hacks – Part 2 (Playing with k’th bit)

In this post we will discuss few related problems that operates on the k’th bit of a number.   Below problems are covered in this post – Problem 1. Turn off kth bit in a number Problem 2. Turn on kth bit in a number Problem 3. Check if kth bit is set for a …

Bit Hacks – Part 1 (Basic)

With this post, we will start a series of amazing bit manipulation hacks that every programmer should know.   Below problems are covered in this post – Problem 1. Check if an given integer is even or odd Problem 2. Detect if two integers have opposite signs or not Problem 3. Add 1 to a …

Generate power set of a given set

Given a set S, generate all subsets of it i.e., find power set of set S. A power set of any set S is the set of all subsets of S, including the empty set and S itself.   For example, if S is the set {x, y, z}, then the subsets of S are: …