Bitwise Operators

Nerd Cafe | نرد کافه

1. Introduction: What Are Bitwise Operators?

Bitwise operators allow you to manipulate individual bits of integers. These are fast, low-level operations often used in:

  • Image processing (e.g., bit masking and pixel thresholding)

  • Feature engineering in machine learning (e.g., encoding multiple Boolean features within a single integer)

  • Performance-critical ML tasks (e.g., efficient binary encoding)

  • Cryptography (e.g., encryption algorithms and hashing)

  • Embedded systems and hardware-level programming (e.g., control registers and flags)

By operating at the bit level, bitwise operations are often faster and more memory-efficient than equivalent arithmetic operations.

2. Bitwise Operators in Python

Operator
Name
Example
Description

&

Bitwise AND

a & b

1 if both bits are 1

|

Bitwise OR

`a | b

1 if either bit is 1 (or both)

^

Bitwise XOR

a ^ b

1 if bits are different

~

Bitwise NOT

~a

Inverts all bits

<<

Left Shift

a << n

Shift bits left, adding 0s on right

>>

Right Shift

a >> n

Shift bits right, discards right bits

3. Working Example: Step-by-Step Demonstration

Step 1: Understanding Binary Representation

Before applying bitwise operators, it is essential to understand binary representations. In Python, the bin() function converts an integer to its binary form (prefixed with 0b).

Here, 10 in decimal is 1010 in binary, and 4 is 0100.

Step 2: Bitwise AND (&)

Explanation:

Only the bits that are 1 in both a and b remain 1 in the result.

Step 3: Bitwise OR (|)

Explanation:

If a bit is set in either operand, it is set in the result.

Step 4: Bitwise XOR (^)

Explanation:

XOR (exclusive OR) returns 1 only if bits differ. It is commonly used in parity checking or change detection.

Step 5: Bitwise NOT (~)

Explanation:

The ~ operator inverts all bits. In Python’s two’s complement system, ~a is equivalent to -(a + 1).

Step 6: Left Shift (<<)

Explanation:

Each left shift multiplies the value by 2. For example, 3 << 1 = 6, 3 << 2 = 12.

Step 7: Right Shift (>>)

Explanation:

Each right shift divides the value by 2 (integer division).

Video Tutorial

Support Our Work

If you find this post helpful and would like to support my work, you can send a donation via TRC-20 (USDT). Your contributions help us keep creating and sharing more valuable content.

Thank you for your generosity! 🙏

Keywords

bitwise operator, bit inversion, two’s complement, Python, binary representation, NOT operator, ~a, negative numbers, bit manipulation, complement, integer encoding, binary arithmetic, bitwise NOT, signed integers, number representation, -(a + 1), data encoding, binary logic, bitwise computation, digital systems, nerd cafe , نرد کافه

Channel Overview

🌐 Website: www.nerd-cafe.ir

📺 YouTube: @nerd-cafe

🎥 Aparat: nerd_cafe

📌 Pinterest: nerd_cafe

📱 Telegram: @nerd_cafe

📝 Blog: Nerd Café on Virgool

💻 GitHub: nerd-cafe

Last updated