0% found this document useful (0 votes)
4 views

bitwise

The document provides a comprehensive guide to C++ bitwise operators, including AND, OR, XOR, NOT, left shift, and right shift, along with their operations, truth tables, examples, and common uses. It also covers practical techniques for bit manipulation, performance considerations, common pitfalls, and advanced techniques like counting set bits and fast exponentiation. Understanding these operators is essential for efficient low-level programming and optimization.

Uploaded by

beyourfacts
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

bitwise

The document provides a comprehensive guide to C++ bitwise operators, including AND, OR, XOR, NOT, left shift, and right shift, along with their operations, truth tables, examples, and common uses. It also covers practical techniques for bit manipulation, performance considerations, common pitfalls, and advanced techniques like counting set bits and fast exponentiation. Understanding these operators is essential for efficient low-level programming and optimization.

Uploaded by

beyourfacts
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Complete Guide to C++ Bitwise Operators

Bitwise operators work on individual bits of integer data types. They're fundamental for low-
level programming, optimization, and bit manipulation.

1. Bitwise AND (&)

Operation: Returns 1 only if both bits are 1, otherwise 0.

Truth Table:

A|B|A&B

--|---|------

0|0| 0

0|1| 0

1|0| 0

1|1| 1

Example:

int a = 12; // 1100 in binary

int b = 10; // 1010 in binary

int result = a & b; // 1000 = 8

Common Uses:

 Masking bits: Extract specific bits from a number

 Check if number is even: num & 1 (returns 0 if even, 1 if odd)

 Clear specific bits: Use with inverted mask

// Check if 3rd bit is set

if (num & (1 << 2)) {

cout << "3rd bit is set\n";

// Check if even
if ((num & 1) == 0) {

cout << "Number is even\n";

2. Bitwise OR (|)

Operation: Returns 1 if at least one bit is 1, otherwise 0.

Truth Table:

A|B|A|B

--|---|------

0|0| 0

0|1| 1

1|0| 1

1|1| 1

Example:

int a = 12; // 1100 in binary

int b = 10; // 1010 in binary

int result = a | b; // 1110 = 14

Common Uses:

 Set specific bits: Turn on particular bits

 Combine flags: Merge multiple boolean flags

// Set 3rd bit

num = num | (1 << 2);

// Combine flags

int permissions = READ_FLAG | WRITE_FLAG | EXECUTE_FLAG;

3. Bitwise XOR (^)

Operation: Returns 1 if bits are di erent, 0 if they're the same.


Truth Table:

A|B|A^B

--|---|------

0|0| 0

0|1| 1

1|0| 1

1|1| 0

Example:

int a = 12; // 1100 in binary

int b = 10; // 1010 in binary

int result = a ^ b; // 0110 = 6

Common Uses:

 Toggle bits: Flip specific bits on/o

 Simple encryption: XOR with key (XOR again to decrypt)

 Swap variables without temp: a ^= b; b ^= a; a ^= b;

// Toggle 3rd bit

num = num ^ (1 << 2);

// Swap without temporary variable

a ^= b;

b ^= a;

a ^= b;

// Simple encryption/decryption

char encrypted = data ^ key;

char decrypted = encrypted ^ key; // Back to original


4. Bitwise NOT (~)

Operation: Flips all bits (1 becomes 0, 0 becomes 1).

Example:

int a = 12; // 00001100 in 8-bit

int result = ~a; // 11110011 = -13 (in two's complement)

Important: Result depends on data type size and signed/unsigned.

Common Uses:

 Create bit masks: ~0 gives all 1s

 Bit clearing: Combined with AND to clear bits

// Create mask with all bits set except 3rd bit

int mask = ~(1 << 2); // ...11111011

// Clear 3rd bit

num = num & ~(1 << 2);

5. Left Shift (<<)

Operation: Shifts bits left by specified positions, filling with zeros.

Example:

int a = 5; // 101 in binary

int result = a << 2; // 10100 = 20

Mathematical Equivalent: a << n equals a * 2^n (for positive numbers).

Common Uses:

 Fast multiplication by powers of 2

 Create bit masks: 1 << n creates mask with only nth bit set

 Set specific bits

// Multiply by 8 (2^3)

int multiplied = num << 3;


// Create mask for 5th bit

int mask = 1 << 4;

// Set multiple bits

int flags = (1 << 2) | (1 << 5) | (1 << 7);

6. Right Shift (>>)

Operation: Shifts bits right by specified positions.

Two Types:

 Logical shift: Fill with zeros (unsigned types)

 Arithmetic shift: Fill with sign bit (signed types)

Example:

int a = 20; // 10100 in binary

int result = a >> 2; // 101 = 5

// For negative numbers (arithmetic shift)

int b = -20;

int result2 = b >> 2; // Sign bit preserved

Mathematical Equivalent: a >> n equals a / 2^n (integer division).

Common Uses:

 Fast division by powers of 2

 Extract specific bit ranges

 E icient algorithms

// Divide by 4 (2^2)

int divided = num >> 2;


// Extract upper 4 bits of a byte

int upper = (byte >> 4) & 0xF;

7. Compound Assignment Operators

All bitwise operators have compound assignment versions:

a &= b; // Equivalent to: a = a & b

a |= b; // Equivalent to: a = a | b

a ^= b; // Equivalent to: a = a ^ b

a <<= n; // Equivalent to: a = a << n

a >>= n; // Equivalent to: a = a >> n

Practical Examples and Techniques

Bit Manipulation Cookbook

// Check if nth bit is set

bool isBitSet(int num, int n) {

return (num & (1 << n)) != 0;

// Set nth bit

int setBit(int num, int n) {

return num | (1 << n);

// Clear nth bit

int clearBit(int num, int n) {

return num & ~(1 << n);

}
// Toggle nth bit

int toggleBit(int num, int n) {

return num ^ (1 << n);

// Count number of set bits

int countSetBits(int num) {

int count = 0;

while (num) {

count += num & 1;

num >>= 1;

return count;

// Check if number is power of 2

bool isPowerOf2(int num) {

return num > 0 && (num & (num - 1)) == 0;

// Find rightmost set bit

int rightmostSetBit(int num) {

return num & -num;

// Clear rightmost set bit


int clearRightmostSetBit(int num) {

return num & (num - 1);

Working with Flags

// Define flags

const int FLAG_READ = 1 << 0; // 001

const int FLAG_WRITE = 1 << 1; // 010

const int FLAG_EXECUTE = 1 << 2; // 100

// Set flags

int permissions = 0;

permissions |= FLAG_READ;

permissions |= FLAG_WRITE;

// Check if flag is set

if (permissions & FLAG_READ) {

cout << "Read permission granted\n";

// Remove flag

permissions &= ~FLAG_WRITE;

// Toggle flag

permissions ^= FLAG_EXECUTE;

Bit Packing (Space Optimization)

// Pack 4 values (0-15) into a single int


struct PackedValues {

int packed;

void setValue(int index, int value) {

// Clear old value and set new one

packed &= ~(0xF << (index * 4));

packed |= (value & 0xF) << (index * 4);

int getValue(int index) {

return (packed >> (index * 4)) & 0xF;

};

Performance Considerations

1. Bitwise operations are extremely fast - usually single CPU instructions

2. Prefer bit operations over arithmetic when possible:

o x << 1 instead of x * 2

o x >> 1 instead of x / 2

o x & 1 instead of x % 2

3. Be careful with signed integers - right shift behavior can be implementation-


defined

4. Use unsigned types for pure bit manipulation to avoid unexpected behavior

Common Pitfalls

1. Operator precedence: Bitwise operators have lower precedence than arithmetic

2. // Wrong: checks if (a + b) equals 0, then ANDs with c

3. if (a + b & c == 0)
4.

5. // Correct: use parentheses

6. if ((a + b) & c == 0)

7. Shifting by negative or large amounts is undefined behavior

8. int a = 5;

9. int result = a << -1; // Undefined behavior

10. int result2 = a << 32; // Undefined if int is 32-bit

11. Signed integer overflow during shifts can cause undefined behavior

Advanced Techniques

Brian Kernighan's Algorithm (Count Set Bits)

int countSetBits(int n) {

int count = 0;

while (n) {

n &= (n - 1); // Clears rightmost set bit

count++;

return count;

Fast Exponentiation using Bits

long long fastPower(long long base, long long exp) {

long long result = 1;

while (exp > 0) {

if (exp & 1) {

result *= base;

base *= base;
exp >>= 1;

return result;

Bitwise operations are powerful tools for e icient programming, especially in systems
programming, embedded development, and competitive programming. Master these
fundamentals and you'll have a solid foundation for advanced bit manipulation techniques!

You might also like