Bitwise Manipulation: Introduction

Let’s go over the Bitwise Manipulation pattern, its real-world applications, and some problems we can solve with it.

About the pattern

In programming, everything is stored in the computer’s memory as sequences of 0s and 1s, which are called bits. Bitwise manipulation is the process of modifying bits algorithmically using bitwise operations. Logical bitwise operations are the fastest computations because processors natively support them. This approach generally leads to efficient solutions in problems where we can efficiently transform the input into its binary form or manipulate it directly at the bit level to produce the required output.

We’ll be focusing on performing bitwise operations on the following two categories of binary numbers:

  • Unsigned binary numbers: These numbers represent nonnegative integers.

  • Signed binary numbers: Signed binary numbers represent both positive and negative integers. They include a sign bit (such as the leftmost bit in two’s complement representationA way of representing signed binary numbers, where the leftmost bit inidicates whether the binary number is positive (0) or negative (1).) to indicate the sign of the number.

A bitwise operation works on a bit stringA string where each character represents a single bit, for example, 10110110., bit arrayAn array where each element represents a single bit, for example, [1, 0, 1, 1, 0, 1, 1, 0]., or a binary numeralA number expressed in the base-2 numeral system, which consists of only two digits: 0 and 1. For example, 10110110.. Bitwise operators take bits as their operandsValues or variables that operators act upon to produce a result. and calculate the corresponding bit value in the result. They include:

  • Logical NOT: This is a unary operatorAn operator that operates on a single operand. that flips the value of the bit. If the bit is 11, we flip it to change a 00 and vice versa. Below is an example of how this operator works on an unsigned binary numeral: