Python Encyclopedia for Academics
  • Course Outline
  • Artificial Intelligence
    • Data Science Foundation
      • Python Programming
        • Introduction and Basics
          • Variables
          • Print Function
          • Input From User
          • Data Types
          • Type Conversion
        • Operators
          • Arithmetic Operators
          • Relational Operators
          • Bitwise Operators
          • Logical Operators
          • Assignment Operators
          • Compound Operators
          • Membership Operators
          • Identity Operators
      • Numpy
        • Vectors, Matrix
        • Operations on Matrix
        • Mean, Variance, and Standard Deviation
        • Reshaping Arrays
        • Transpose and Determinant of Matrix
      • Pandas
        • Series and DataFrames
        • Slicing, Rows, and Columns
        • Operations on DataFrames
        • Different wayes to creat DataFrame
        • Read, Write Operations with CSV files
      • Matplotlib
        • Graph Basics
        • Format Strings in Plots
        • Label Parameters, Legend
        • Bar Chart, Pie Chart, Histogram, and Scatter Plot
  • Machine Learning Algorithms
    • Regression Analysis In ML
      • Regression Analysis in Machine Learning
      • Proof of Linear Regression Formulas
      • Simple Linear Regression Implementation
      • Multiple Linear Regression
      • Advertising Dataset Example
      • Bike Sharing Dataset
      • Wine Quality Dataset
      • Auto MPG Dataset
    • Classification Algorithms in ML
      • Proof of Logistic Regression
      • Simplified Mathematical Proof of SVM
      • Iris Dataset
  • Machine Learning Laboratory
    • Lab 1: Titanic Dataset
      • Predicting Survival on the Titanic with Machine Learning
    • Lab 2: Dow Jones Index Dataset
      • Dow Jones Index Predictions Using Machine Learning
    • Lab 3: Diabetes Dataset
      • Numpy
      • Pandas
      • Matplotlib
      • Simple Linear Regression
      • Simple Non-linear Regression
      • Performance Matrix
      • Preprocessing
      • Naive Bayes Classification
      • K-Nearest Neighbors (KNN) Classification
      • Decision Tree & Random Forest
      • SVM Classifier
      • Logistic Regression
      • Artificial Neural Network
      • K means Clustering
    • Lab 4: MAGIC Gamma Telescope Dataset
      • Classification in ML-MAGIC Gamma Telescope Dataset
    • Lab 5: Seoul Bike Sharing Demand Dataset
      • Regression in ML-Seoul Bike Sharing Demand Dataset
    • Lab 6: Medical Cost Personal Datasets
      • Predict Insurance Costs with Linear Regression in Python
    • Lab 6: Predict The S&P 500 Index With Machine Learning And Python
      • Predict The S&P 500 Index With Machine Learning And Python
  • Artificial Neural Networks
    • Biological Inspiration vs. Artificial Neurons
    • Review linear algebra and calculus essentials for ANNs
    • Activation Function
  • Mathematics
    • Pre-Calculus
      • Factorials
      • Roots of Polynomials
      • Complex Numbers
      • Polar Coordinates
      • Graph of a Function
    • Calculus 1
      • Limit of a Function
      • Derivative of Function
      • Critical Points
      • Indefinite Integrals
  • Calculus 2
    • 3D Coordinates and Vectors
    • Vectors and Vector Operations
    • Lines and Planes in Space (3D)
    • Partial Derivatives
    • Optimization Problems (Maxima/Minima) in Multivariable Functions
    • Gradient Vectors
  • Engineering Mathematics
    • Laplace Transform
  • Electrical & electronics Eng
    • Resistor
      • Series Resistors
      • Parallel Resistors
    • Nodal Analysis
      • Example 1
      • Example 2
    • Transient State
      • RC Circuit Equations in the s-Domain
      • RL Circuit Equations in the s-Domain
      • LC Circuit Equations in the s-Domain
      • Series RLC Circuit with DC Source
  • Computer Networking
    • Fundamental
      • IPv4 Addressing
      • Network Diagnostics
  • Cybersecurity
    • Classical Ciphers
      • Caesar Cipher
      • Affine Cipher
      • Atbash Cipher
      • Vigenère Cipher
      • Gronsfeld Cipher
      • Alberti Cipher
      • Hill Cipher
Powered by GitBook
On this page
  • What Are Bitwise Operators?
  • Bitwise Operators in Python
  • Step-by-Step with Examples
  • Machine Learning Use Cases
  • Practical Notes
  • Keywords
  1. Artificial Intelligence
  2. Data Science Foundation
  3. Python Programming
  4. Operators

Bitwise Operators

Nerd Cafe

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

  • Feature engineering (e.g., bitmasking)

  • Performance-critical ML tasks

  • Cryptography

  • Embedded systems

Bitwise Operators in Python

Operator
Name
Example
Description

&

AND

a & b

1 if both bits are 1

|

OR

a | b

1 if either bit is 1 (or both)

^

XOR

a ^ b

1 if bits are different

~

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

Step-by-Step with Examples

Step 1: Understand Binary Format in Python

Before applying bitwise ops, you should know how integers are stored in binary.

a = 10
b = 4

print(bin(a))  # 0b1010
print(bin(b))  # 0b100

bin() function returns the binary string of a number prefixed with 0b.

Step 2: Bitwise AND (&)

a = 10        # 1010
b = 4         # 0100

result = a & b
print(result)  # 0b0000 => 0

Use Case in ML: Masking selected bits in a bit pattern (e.g., enabling specific features only).

Step 3: Bitwise OR (|)

a = 10        # 1010
b = 4         # 0100

result = a | b
print(result)  # 0b1110 => 14

Use Case in ML: Combining binary feature flags.

Step 4: Bitwise XOR (^)

a = 10        # 1010
b = 4         # 0100

result = a ^ b
print(result)  # 0b1110 => 14

Use Case in ML: Change detection, feature toggles — highlight differences between two feature sets.

Step 5: Bitwise NOT (~)

a = 10         # 1010

result = ~a
print(result)  # -11

Use Case: Inverting bits, e.g., selecting the complement of a feature mask.

Step 6: Bitwise Left Shift (<<)

a = 3         # 0011

result = a << 2
print(result)  # 001100 => 12

Use Case: Efficient multiplication (e.g., a << 1 is like a * 2)

Step 7: Bitwise Right Shift (>>)

a = 8         # 1000

result = a >> 2
print(result)  # 0010 => 2

Use Case: Efficient division (e.g., a >> 1 is like a / 2)

Machine Learning Use Cases

1. Encoding Categorical Values Compactly

Bitwise encoding is sometimes used to store categorical or binary data compactly.

# Represent 'Red' = 0b0001, 'Blue' = 0b0010, 'Green' = 0b0100
RED = 1
BLUE = 2
GREEN = 4

# Let's say an object has RED and GREEN properties
color = RED | GREEN  # => 0b0101

# Check if it contains RED
print(bool(color & RED))   # True
# Check if it contains BLUE
print(bool(color & BLUE))  # False

2. Fast Image Processing (Pillow + NumPy + Bitwise)

import numpy as np
from PIL import Image

img = Image.open("your_image.jpg").convert("L")  # grayscale
np_img = np.array(img)

# Highlight dark pixels using a bitwise threshold
mask = (np_img & 0b11110000) == 0
np_img[mask] = 255  # highlight them in white

Image.fromarray(np_img).show()

Practical Notes

Topic
Note

Speed

Bitwise operations are faster than arithmetic counterparts

Compatibility

Only works on integers (not floats)

NumPy Support

Use np.bitwise_and, np.left_shift, etc. for vectorized ops

Safety

Always make sure shifts don't go beyond bit width

ML Use

Useful in binary encoding, feature flags, data compression

Keywords

bitwise operators, python bitwise, bitwise and, bitwise or, bitwise xor, bitwise not, left shift, right shift, binary operations, bitmasking, feature flags, fast computation, binary encoding, low-level operations, image processing, numpy bitwise, feature selection, binary logic, machine learning optimization, python binary tools, nerd cafe

PreviousRelational OperatorsNextLogical Operators

Last updated 2 months ago