Category Archives: Bit Magic

Builtin functions of GCC compiler

These are three important builtin functions in GCC compiler: _builtin_popcount(x): This function is used to count the number of one’s(set bits) in an integer. Example: if x = 4 binary value of 4 is 100 Output: No of ones is 1. Output: Count of 1s in binary of 5 is 2 __builtin_clz(x): This function is… Read More »

Count all pairs of an array which differ in K bits

Given an array of size n and integer k, count all pairs in array which differ in exactly K bits of binary representation of both the numbers. The input arrays have elements with small values and possibly many repetitions. Input: arr[] = {2, 4, 1, 3, 1} k = 2 Output: 5 Explanation: There are… Read More »

Count trailing zero bits using lookup table

Given an integer, count the number of trailing zeroes. For example, for n = 12, its binary representation is 1100 and number of trailing zero bits is 2. Examples: Input : 8 Output : 3 Binary of 8 is 1000, so there are theree trailing zero bits. Input : 18 Output : 1 Binary of… Read More »

Check divisibility in a binary stream

Stream of binary number is coming, the task is to tell the number formed so far is divisible by a given number n. At any given time, you will get 0 or 1 and tell whether the number formed with these bits is divisible by n or not. Generally, e-commerce companies ask this type of… Read More »

Multiplication of two numbers with shift operator

For any given two numbers n and m, you have to find n*m without using any multiplication operator. Examples: Input: n = 25 , m = 13 Output: 325 Input: n = 50 , m = 16 Output: 800 We can solve this problem with the shift operator. The idea is based on the fact… Read More »