Algorithmsencoding trick
Encoding Tricks (Char to Int, Bitmasks, Small Alphabets)
TT
Testlaa Team
May 14, 2026•1 min read
Encoding tricks map characters to small integers so arrays or XOR tricks work—classic examples: (ord(ch)-ord('a')) for 26-letter bitmasking, or pairing two letters into one number for DP state compression.
Why this shows up in the real world
Genetic pipelines encode A,C,G,T as 0..3 in packed arrays. Keyboard layout optimizers score keys numerically for search algorithms.
Core idea (explained for students)
Bitmask for lowercase set: bits |= 1 << (ord(c)-ord('a')). To test membership: bits & (1<<k). Reverse map with chr(ord('a')+k) when only one bit is set.
Try this in Python
def mask_from_lowercase(s: str) -> int:
bits = 0
for c in s:
if "a" <= c <= "z":
bits |= 1 << (ord(c) - ord("a"))
return bits
print(bin(mask_from_lowercase("face")))
Common mistakes
- Integer overflow in languages with fixed-width ints—Python big ints help but still mind complexity.
- Mixing uppercase and lowercase encodings without normalizing first.
Key takeaways
- Encoding is a design choice—document the alphabet size and mapping table.
- Prefer tuples of small ints over giant bitmasks when readability wins.
Tags:
StringsPythonStudents
