Bitmasking - 1

Covered in this section:

Introduction

All data in computer programs is internally stored as bits, i.e., as numbers 0 and 1. Bitmasking/Bitmanipulation involves directly working with individual bits (0s and 1s) using operations like AND, OR, XOR, and NOT :

AND operation

The and operation x & y produces a number that has one bits in positions where both x and y have one bits. For example, 22 & 26 = 18, because

OR operation

The or operation x | y produces a number that has one bits in positions where at least one of x and y have one bits.

XOR operation

The xor operation x ^ y produces a number that has one bits in positions where exactly one of x and y have one bits.

NOT operation

The not operation ~x produces a number where all the bits of x have been inverted. NOT in bitmasking is a tricky operator as its representation depends on size of data structure


            x = 29 => 00000000000000000000000000011101
            ~x = −30 => 11111111111111111111111111100010
        

Basic Bit Operations

C++ STL

Practice Assignment

Next Lesson