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
&
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.
bin()
function returns the binary string of a number prefixed with 0b
.
Step 2: Bitwise AND (&
)
&
)Use Case in ML: Masking selected bits in a bit pattern (e.g., enabling specific features only).
Step 3: Bitwise OR (|
)
|
)Use Case in ML: Combining binary feature flags.
Step 4: Bitwise XOR (^
)
^
)Use Case in ML: Change detection, feature toggles — highlight differences between two feature sets.
Step 5: Bitwise NOT (~
)
~
)Use Case: Inverting bits, e.g., selecting the complement of a feature mask.
Step 6: Bitwise Left Shift (<<
)
<<
)Use Case: Efficient multiplication (e.g., a << 1
is like a * 2
)
Step 7: Bitwise Right Shift (>>
)
>>
)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.
2. Fast Image Processing (Pillow + NumPy + Bitwise)
Practical Notes
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
Last updated