Count Set Bits of a Number in C

A number consists of multiple bits in its binary representation. For example, an integer would have 32 bits and a long would have 64 bits on 64-bit system. Bit values could either be 0 (not set) or 1 (set). From the diagram above, we can see that the binary representation of 2392 has 5 set … Continue reading “Count Set Bits of a Number in C”

Brian Kernighan’s Algorithm to Count the Set Bits of a Number

To count all set bits of a number, we can loop through all the bits and check whether any bit is set. For example, an integer has 32 bits. We can check all 32 bits in a loop to count the set (1) bits. Here will see how we can improve this mechanism using Brian … Continue reading “Brian Kernighan’s Algorithm to Count the Set Bits of a Number”

Left and Right Rotate Bits of a Number in C

Here we’ll see how to write C program to left or right rotate bits of a number. For example, an unsigned integer consists of 32-bit. Number 2591458749 is represented as 10011010011101101000010110111101 in binary. The diagram below shows how the bits of that number will look like after rotating 8 bits. Logic to Left Rotate Bits … Continue reading “Left and Right Rotate Bits of a Number in C”

C Program to Toggle Bits

Here we’ll see how to write C program to toggle all bits or a particular bit or all but a particular bit of a number. Toggle All Bits of a Number We can toggle all bits of a number using NOT (~) bitwise operation. Doing NOT (~) operation on a number toggles all of its … Continue reading “C Program to Toggle Bits”

C Program to Set, Clear and Toggle a Bit

In this article we saw how to check a particular bit of a number. Here we’ll see how to set, clear or toggle a bit of a number. Setting a Bit Setting a bit means making that bit 1 irrespective of the previous value of that bit. We can use bitwise operation OR (|) to … Continue reading “C Program to Set, Clear and Toggle a Bit”

0
1
0
6
7
4