Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. Two bits per base
    4. Sliding along a read
    5. Skipping N
    6. The other strand: reverse complement
    7. Canonical k-mers
    8. Counting k-mers
    9. Which one should I use?
    10. Under the hood
    11. Common pitfalls
    12. A mask for k = 32
    13. Try it yourself

    Module 12 · C++ for bioinformatics

    12.22-bit DNA and k-mers

    Pack a k-mer of up to 32 bases into one 64-bit integer, slide it along a read with a shift and a mask, handle the other DNA strand and unreadable bases, and count k-mers in a hash map or a flat table.

    About 30 minutesIntermediate

    On this page
    1. Key terms
    2. In 30 seconds
    3. Two bits per base
    4. Sliding along a read
    5. Skipping N
    6. The other strand: reverse complement
    7. Canonical k-mers
    8. Counting k-mers
    9. Which one should I use?
    10. Under the hood
    11. Common pitfalls
    12. A mask for k = 32
    13. Try it yourself

    Key terms

    k-mer
    A piece of DNA k bases long. A read of n bases has n - k + 1 of them, one starting at each position.
    2-bit encoding
    Storing each base as a 2-bit code: A = 00, C = 01, G = 10, T = 11. A std::uint64_t holds 32 bases.
    rolling encoding
    Updating a packed k-mer as the window slides one base: shift the oldest base out and the new one in, instead of encoding all k bases again.
    complement
    The base paired with a base on the other DNA strand: A with T, C with G.
    reverse complement
    A sequence read backwards with every base complemented: the same stretch of DNA, read from the other strand.
    canonical k-mer
    The smaller of a k-mer and its reverse complement, so a k-mer and its copy on the other strand count as one.
    N
    The letter sequencers write for a base they couldn't read.
    flat count table
    A vector with one counter for every possible k-mer (4^k of them), indexed by the packed k-mer itself.

    Many tools in genomics start by cutting reads into k-mers, short pieces of DNA k bases long, and counting them: to assemble a genome, to find sequencing errors, or to tell which species a read came from. A sequencing run can hold billions of k-mers, so how you store one matters. As a std::string, a 21-mer costs a heap allocation. Packed at 2 bits per base, it’s one std::uint64_t that compares, hashes and indexes like any number.

    In 30 seconds

    • Each base fits in 2 bits, so a k-mer of up to 32 bases fits in one std::uint64_t.
    • Sliding to the next k-mer is one shift, one OR and one mask, not k steps.
    • The reverse complement flips every code (~) and reverses their order. The smaller of the two is the canonical k-mer, the same on both strands.
    • Count with a std::unordered_map<std::uint64_t, int>, or, for small k, with a flat vector of 4^k counters indexed by the k-mer.

    Two bits per base

    Operators and bit operations packed four bases into a byte: A = 00, C = 01, G = 10, T = 11, shifting left by 2 and ORing in each new code. A std::uint64_t has room for 32 bases. Here a base’s code is its index in the string "ACGT", which find gives you; constexpr builds a lookup table that does the same with one array read.

    #include <cstddef>
    #include <cstdint>
    #include <print>
    #include <string>
    #include <string_view>
    
    constexpr std::string_view bases = "ACGT"; // a base's code is its index
    
    std::uint64_t pack(std::string_view kmer) {
        std::uint64_t packed = 0;
        for (char base : kmer) {
            packed = (packed << 2) | bases.find(base);
        }
        return packed;
    }
    
    std::string unpack(std::uint64_t packed, std::size_t k) {
        std::string kmer(k, 'A');
        for (std::size_t i = k; i > 0; --i) {
            kmer[i - 1] = bases[packed & 0b11]; // the last base is lowest
            packed >>= 2;
        }
        return kmer;
    }
    
    int main() {
        std::uint64_t code = pack("GATTACA");
        std::println("{:014b} = {}", code, code);
        std::println("{}", unpack(code, 7));
        std::println("{}", unpack(pack("TTTTGGGGCCCCAAAATTTTGGGGCCCCAAAA"), 32));
    }

    Output

    10001111000100 = 9156
    GATTACA
    TTTTGGGGCCCCAAAATTTTGGGGCCCCAAAA

    The first base ends up in the highest bits and the last base in the lowest two. unpack needs k, because the number alone doesn’t say how many leading As (00) it has: A, AA and AAA all pack to 0. So never mix k-mers of different lengths in one table, and keep k next to any packed k-mer you store. One more property makes this encoding useful: the codes are in alphabetical order, A < C < G < T. Comparing two packed k-mers of the same length as numbers gives the same answer as comparing them as strings.

    Sliding along a read

    A read of n bases has n - k + 1 k-mers, one starting at each position. Packing each one from scratch costs k steps per position. A rolling encoding reuses the previous k-mer instead: shift it left by 2, OR in the new base, and mask off the base that slid out of the window. Each step costs the same whatever k is. The mask has the low 2k bits set; ~std::uint64_t{0} is all 64 bits set, and shifting it right by 64 - 2k leaves 2k of them:

    #include <cstddef>
    #include <cstdint>
    #include <print>
    #include <string_view>
    
    constexpr std::string_view bases = "ACGT";
    std::string_view read = "GATTACA";
    std::size_t k = 3;
    std::uint64_t mask = ~std::uint64_t{0} >> (64 - 2 * k);
    std::uint64_t kmer = 0;
    for (std::size_t i = 0; i < read.size(); ++i) {
        kmer = ((kmer << 2) | bases.find(read[i])) & mask;
        if (i + 1 >= k) { // the window holds k bases
            std::println("{} {:06b} {}", read.substr(i + 1 - k, k), kmer, kmer);
        }
    }

    Output

    GAT 100011 35
    ATT 001111 15
    TTA 111100 60
    TAC 110001 49
    ACA 000100 4

    Skipping N

    Real reads contain N where the sequencer couldn’t tell the base. No 2-bit code means “unknown”, so a k-mer that covers an N is skipped. Count how many valid bases have arrived since the last N, and only use the k-mer once that count reaches k:

    #include <cstddef>
    #include <cstdint>
    #include <print>
    #include <string_view>
    
    constexpr std::string_view bases = "ACGT";
    std::string_view read = "ACGTNACGTA";
    std::size_t k = 3;
    std::uint64_t mask = ~std::uint64_t{0} >> (64 - 2 * k);
    std::uint64_t kmer = 0;
    std::size_t valid = 0; // bases since the last N
    for (char base : read) {
        std::size_t code = bases.find(base);
        if (code == std::string_view::npos) {
            valid = 0; // an N, or any other letter: start again
            continue;
        }
        kmer = ((kmer << 2) | code) & mask;
        if (++valid >= k) {
            std::print("{} ", kmer);
        }
    }
    std::println("");

    Output

    6 27 6 27 44

    ACG (6) and CGT (27) appear on both sides of the N, and the k-mers that would cross it are skipped. Some files write repeats in lowercase (acgt); this code treats those letters like N, so convert them to uppercase first if you want to count them.

    The other strand: reverse complement

    DNA has two strands, read in opposite directions, and A pairs with T and C with G. A read can come from either strand, so the k-mer GAT on one strand is ATC on the other: reversed, with every base replaced by its complement. That’s the reverse complement. The 2-bit codes make the complement cheap: A (00) and T (11), C (01) and G (10) are each other with both bits flipped, so ~ complements every base at once. Reversing means taking bases off the low end of one number and adding them at the low end of another (pack and unpack are as above):

    #include <cstddef>
    #include <cstdint>
    #include <print>
    #include <string>
    #include <string_view>
    
    constexpr std::string_view bases = "ACGT";
    
    std::uint64_t reverse_complement(std::uint64_t kmer, std::size_t k) {
        std::uint64_t rc = 0;
        for (std::size_t i = 0; i < k; ++i) {
            rc = (rc << 2) | (~kmer & 0b11); // complement of the lowest base
            kmer >>= 2;
        }
        return rc;
    }
    
    int main() {
        std::uint64_t kmer = pack("GATTACA");
        std::println("{}", unpack(reverse_complement(kmer, 7), 7));
    }

    Output

    TGTAATC

    Canonical k-mers

    To count a k-mer and its copy on the other strand as one, use the canonical k-mer: the smaller of the k-mer and its reverse complement. Because the codes are in alphabetical order, “smaller” means first alphabetically. The reverse complement can roll along the read too. A new base enters the forward k-mer at the low end, so its complement enters the reverse complement at the high end, at bit 2(k - 1), while the oldest base falls off the low end. Here are the canonical k-mers of a read and of its reverse complement:

    #include <algorithm>
    #include <cstddef>
    #include <cstdint>
    #include <print>
    #include <string>
    #include <string_view>
    #include <vector>
    
    constexpr std::string_view bases = "ACGT";
    
    std::vector<std::uint64_t> canonical_kmers(std::string_view read,
                                               std::size_t k) {
        std::uint64_t mask = ~std::uint64_t{0} >> (64 - 2 * k);
        std::uint64_t fwd = 0;
        std::uint64_t rev = 0;
        std::size_t valid = 0;
        std::vector<std::uint64_t> result;
        for (char base : read) {
            std::uint64_t code = bases.find(base);
            if (code == std::string_view::npos) {
                valid = 0;
                continue;
            }
            fwd = ((fwd << 2) | code) & mask;
            rev = (rev >> 2) | ((code ^ 0b11) << (2 * (k - 1)));
            if (++valid >= k) {
                result.push_back(std::min(fwd, rev));
            }
        }
        return result;
    }
    
    int main() {
        for (std::string_view read : {"GATTACA", "TGTAATC"}) {
            std::vector<std::string> names;
            for (std::uint64_t kmer : canonical_kmers(read, 3)) {
                names.push_back(unpack(kmer, 3));
            }
            std::println("{} {}", read, names);
        }
    }

    Output

    GATTACA ["ATC", "AAT", "TAA", "GTA", "ACA"]
    TGTAATC ["ACA", "GTA", "TAA", "AAT", "ATC"]

    TGTAATC is the reverse complement of GATTACA. Their plain k-mers share nothing, but their canonical k-mers are the same five, in opposite order. code ^ 0b11 complements a single code (~ would also flip the 62 bits above it).

    Counting k-mers

    Maps and sets counted k-mers with a std::map<std::string, int>. With packed k-mers, the key is a std::uint64_t, and there are two good ways to count:

    • A std::unordered_map<std::uint64_t, int> stores only the k-mers that appear. It works for any k up to 32.
    • A flat count table, a std::vector<int> with 4^k counters, uses the packed k-mer itself as the index: no hashing, no searching. It only works while 4^k counters fit in memory.
    #include <cstddef>
    #include <cstdint>
    #include <print>
    #include <string>
    #include <string_view>
    #include <unordered_map>
    #include <vector>
    
    constexpr std::string_view bases = "ACGT";
    
    int main() {
        std::vector<std::string_view> reads = {"GATTACA", "ACAGATNTACA", "TGTAATC"};
        std::size_t k = 3;
        std::unordered_map<std::uint64_t, int> counts;
        std::vector<int> table(std::size_t{1} << (2 * k)); // 4^k counters
        for (std::string_view read : reads) {
            for (std::uint64_t kmer : canonical_kmers(read, k)) {
                ++counts[kmer];
                ++table[kmer];
            }
        }
        for (std::uint64_t kmer = 0; kmer < table.size(); ++kmer) {
            if (table[kmer] > 0) {
                std::println("{} {} {}", unpack(kmer, k), table[kmer],
                             counts[kmer]);
            }
        }
        std::println("{} different k-mers, {} slots", counts.size(), table.size());
    }

    Output

    AAT 2 2
    ACA 4 4
    AGA 1 1
    ATC 3 3
    CAG 1 1
    GTA 3 3
    TAA 2 2
    7 different k-mers, 64 slots

    canonical_kmers is the function from the previous section. Both counts agree. Walking the flat table from index 0 lists the k-mers in alphabetical order for free; a std::unordered_map has no useful order, so sort its entries before printing them. Hashing a std::uint64_t is also cheap: GCC’s standard library uses the number itself as the hash, where a std::string key has to hash every character.

    Which one should I use?

    WhatWhenWhyHow
    std::string k-mersSmall inputs, a quick script, or k over 32.Easy to read and print; no limit on k.std::map<std::string, int>, ++counts[read.substr(i, k)]
    Packed k-mers in a std::unordered_mapAny k up to 32, many reads.8 bytes per key, fast to hash and compare, and only k-mers that appear take memory.std::unordered_map<std::uint64_t, int>
    A flat count tableSmall k, roughly up to 12 to 14.Counting is one array increment, and the table is already in alphabetical order.std::vector<int> table(std::size_t{1} << (2 * k))

    Rule of thumb: pack k-mers whenever k is 32 or less; count in a flat table when 4^k counters fit comfortably in memory, and in a hash map otherwise. For k above 32, tools use two std::uint64_t words or a 128-bit integer.

    Under the hood

    What does one k-mer cost? A 21-mer is a common choice in genome tools:

    #include <cstdint>
    #include <print>
    #include <string>
    
    std::string kmer(21, 'A');
    std::println("std::string: {} bytes, plus {} on the heap", sizeof(kmer),
                 kmer.capacity() + 1);
    std::println("packed: {} bytes", sizeof(std::uint64_t));
    for (int k : {8, 12, 14}) {
        double bytes = static_cast<double>(std::uint64_t{1} << (2 * k)) * 4;
        std::println("flat table for k = {}: {} MiB", k, bytes / (1 << 20));
    }

    Output

    std::string: 32 bytes, plus 22 on the heap
    packed: 8 bytes
    flat table for k = 8: 0.25 MiB
    flat table for k = 12: 64 MiB
    flat table for k = 14: 1024 MiB

    With GCC’s standard library, a std::string is 32 bytes. Text longer than 15 characters doesn’t fit inside the object (string and string_view shows the small-string optimization), so a 21-mer also needs its own heap block. Packed, it’s 8 bytes with nothing on the heap. A flat table of 4-byte counters grows by four times with each extra base: comfortable at k = 12, a gigabyte at k = 14.

    A hash map adds its own cost per entry. GCC’s std::unordered_map stores each entry in a separate heap node, with the key, the count and a pointer to the next node, plus an array of buckets. For a billion k-mers, that overhead decides whether the counts fit in memory, which is why large counting tools use their own compact hash tables. Processing reads in parallel splits the counting across threads.

    Common pitfalls

    A mask for k = 32

    The obvious mask, (1 << 2k) - 1, works up to k = 31. At k = 32 it shifts a 64-bit value by 64 places, which is undefined behavior (Operators and bit operations showed the same with 32 bits). UndefinedBehaviorSanitizer stops it:

    #include <cstddef>
    #include <cstdint>
    #include <print>
    
    std::size_t k = 32;
    std::uint64_t mask = (std::uint64_t{1} << (2 * k)) - 1;
    std::println("{:x}", mask);

    This fails when it runs

    main.cpp:6:40: runtime error: shift exponent 64 is too large for 64-bit type 'long unsigned int'

    The fix is the mask used in this lesson, ~std::uint64_t{0} >> (64 - 2 * k), which shifts by 0 when k is 32. It still needs k of at least 1.

    Try it yourself

    Try it yourself

    mismatches should count the positions where two k-mers of the same length have different bases. It counts differing bits instead, so GATTACA and GTTTACA, one base apart, get 2. Fix it so it counts bases.

    #include <bit>
    #include <cstdint>
    #include <print>
    #include <string_view>
    
    constexpr std::string_view bases = "ACGT";
    
    std::uint64_t pack(std::string_view kmer) {
        std::uint64_t packed = 0;
        for (char base : kmer) {
            packed = (packed << 2) | bases.find(base);
        }
        return packed;
    }
    
    int mismatches(std::uint64_t a, std::uint64_t b) {
        return std::popcount(a ^ b);
    }
    
    int main() {
        std::println("{}", mismatches(pack("GATTACA"), pack("GTTTACA")));
        std::println("{}", mismatches(pack("GATTACA"), pack("GACTATA")));
    }

    Expected output

    1
    2
    Show a hint

    A base differs when either of its two bits differs. diff | (diff >> 1) moves each pair's high bit onto its low bit; & 0x5555'5555'5555'5555 (binary 0101...) keeps only the low bit of each pair. Then count with std::popcount.

    Show a solution
    #include <bit>
    #include <cstdint>
    #include <print>
    #include <string_view>
    
    constexpr std::string_view bases = "ACGT";
    
    std::uint64_t pack(std::string_view kmer) {
        std::uint64_t packed = 0;
        for (char base : kmer) {
            packed = (packed << 2) | bases.find(base);
        }
        return packed;
    }
    
    int mismatches(std::uint64_t a, std::uint64_t b) {
        std::uint64_t diff = a ^ b;
        std::uint64_t per_base = (diff | (diff >> 1)) & 0x5555'5555'5555'5555;
        return std::popcount(per_base);
    }
    
    int main() {
        std::println("{}", mismatches(pack("GATTACA"), pack("GTTTACA")));
        std::println("{}", mismatches(pack("GATTACA"), pack("GACTATA")));
    }

    a ^ b has a 1 in every bit that differs. An A/T or C/G mismatch differs in both bits of its pair, so std::popcount(a ^ b) counts it twice. Folding each pair onto its low bit and masking leaves exactly one bit per mismatched base, and std::popcount counts the bases.

    Saved in this browser only.