Skip to main content
ProductsDesktop toolsTASTECADDrawing reviewTASTEFILESFile managementTASTEFTPFile transferTASTESSHRemote workspaceTASTEZIPCompression and extractionTASTEWINMFile managementDeveloper toolsTASTECODERust integrated development environmentTASTESTUDIOIntegrated development and test environmentTASTEETLData integration (ETL)ServersTASTEREMOTERemote desktop serverTASTEGEOGeospatial serverTASTEMAILMail workspaceInvestingTASTESTOCKStock auto-trading desktop appGet startedDownloadsDocumentationBuyAll products
Marketplace
News
TechNewsToday's dev newsDeveloper docsProgramming languagesRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp & desktop frameworksTauriFlutterReact NativeElectronAlgorithmsAlgorithm basicsCore algorithmsAdvanced algorithmsPractical algorithms
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcaseCommunity guide
Work with usTech transferWebsite buildDesktop app buildRelease and payment pipelineSales partnerContact
ServicesRemote desktopCustom installer packages
TASTEDEV
Products

Desktop tools

TASTECADComplex drawings, opened with easeTASTEFILESJust the files you need, as fast as possibleTASTEFTPThe tidiest path for your filesTASTESSHA stronger link between you and your serversTASTEZIPPack faster, unpack saferTASTEWINMA keyboard-first file manager with two panes

Developer tools

TASTECODEEdit, build, debug and test Rust apps in one windowTASTESTUDIOFrom editing to remote tests and approved AI fixesTASTEETLMove data while you watch the values

Servers

TASTEREMOTEA remote desktop you run on your own serverTASTEGEORebuilding a GeoServer-compatible geospatial server in RustTASTEMAILTake back control of your email

Investing

TASTESTOCKStock auto-trading that follows the rules you set: when, and what

Get started

DownloadsLatest builds of every productDocsHow to use each productBuySubscriptions and perpetual licencesAll productsEvery product at a glance
All products
MarketplaceNews
Tech

News

Today's dev newsOfficial announcements on languages, frameworks, GitHub and AIDeveloper docsGuides to languages, frameworks and algorithms

Programming languages

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App & desktop frameworksTauriFlutterReact NativeElectron

Algorithms

Algorithm basicsComplexity analysis · Sorting · Searching · Basic data structures · Trees and heapsCore algorithmsGraph traversal · Shortest paths & minimum spanning trees · Dynamic programming · Greedy algorithms · Divide and conquer · BacktrackingAdvanced algorithmsString algorithms · Math and number theory · Bit manipulation · Segment trees · Union-findPractical algorithmsCoding interview strategy · LRU cache · Rate limiting · Consistent hashing
All development docs
Community
ProjectsDiscover builders and their workDevelopment logsDecisions and lessons learnedPromptsReusable instructionsAI tool issuesProblems and workarounds for Claude, Codex, GeminiShowcaseFinished resultsCommunity guideHow we build in the open
Work with us
Tech transferNative apps in Rust and eguiWebsite build10 languages, accounts, docs and downloadsDesktop app buildRust and egui, no WebViewRelease and payment pipelineSigning, MSI, deb, rpm, AppImage, hashesSales partnerRecommend us and earn 30%ContactBuilds, partnerships and investment
Services
Remote desktopReach your computer from a browserCustom installer packagesOnly the features you need, settings preloaded
Buy
EN
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Log in
Log in
TASTEDEV

From small tools to better development.

support@tastedev.netSupport TASTEDEV
ProductsProduct lineupBuyDocsDownloadsMarketplaceSupport
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcase
PoliciesAbout usPrivacy policyTerms of serviceSubscription termsRefund policyCommunity guidelines
AccountLog inSign up
Visitors
Today
Yesterday
Total views
Company
GXSOFT
Representative
CHOI YOUNG GU
Business registration number
853-44-00368
Address
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Phone
+82-10-4404-1523
Email
whitecalvin@tastedev.net
Privacy officer
CHOI YOUNG GU

© 2026 TASTEDEVProduct information is based on verified development sources.Released · improving

Bit manipulation docs
Bit manipulation
ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
Discussions

Bit manipulation guide · 4/6

Complexity

A single bitwise operation is one machine instruction, so on fixed-width integers it is O(1). What matters is how many times you repeat it and how many states a mask can describe. This chapter compares popcount strategies, measures subset and submask enumeration, and shows where bitmask DP stops being practical.

Basic operations

On w-bit integers, AND, OR, XOR, NOT, shifts, x & -x and x & (x - 1) all take O(1) time and space. Python integers are unbounded, so strictly an operation costs O(b) for a b-bit value, but anything that fits in 64 bits is effectively constant.

Popcount strategies

MethodTimeNotes
Check every bitO(w)simplest, always w rounds
Kernighan (x &= x - 1)O(k), k = set bitsfast for sparse values, worst case O(w)
8-bit lookup tableO(w / 8)needs a 256-entry table
SWAR parallel sumO(log w)branch-free shifts and adds
Hardware POPCNTO(1)used by int.bit_count, std::popcount, Integer.bitCount
def popcount_swar(x: int) -> int:
    # unsigned 32-bit values only
    x = x - ((x >> 1) & 0x55555555)
    x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
    x = (x + (x >> 4)) & 0x0F0F0F0F
    return ((x * 0x01010101) & 0xFFFFFFFF) >> 24

assert all(popcount_swar(v) == v.bit_count() for v in (0, 1, 255, 2**32 - 1, 0xDEADBEEF))

If you need the popcount of every number from 0 to n, fill a table in O(n) with bits[i] = bits[i >> 1] + (i & 1).

Subset enumeration

With n items there are 2^n masks; testing n bits per mask costs O(2^n * n) time. Collecting every subset in a list also costs O(2^n * n) space, while a generator needs only O(n). Rough limits:

n2^n2^n * nFeel
101,024about 10 thousandinstant
1665,536about 1 millionfast
20about 1.05 millionabout 21 milliontens of ms in C++, seconds in Python
25about 33.5 millionabout 840 millionimpractical in Python
40about 1.1 trillion-needs meet in the middle

Submasks and 3^n

Looping over every mask and then over its submasks looks like O(4^n), but it is O(3^n): each item is either outside the mask, in the mask only, or in both mask and submask. For n = 15, 3^15 is about 14 million, which is fine.

n = 4
pairs = 0
for mask in range(1 << n):
    sub = mask
    while True:
        pairs += 1
        if sub == 0:
            break
        sub = (sub - 1) & mask
print(pairs, 3 ** n)   # 81 81

Subsets of a fixed size

If you only need subsets of size k, scanning all 2^n masks and filtering by popcount still costs O(2^n). When C(n, k) is much smaller than 2^n, generating combinations directly, as itertools.combinations does, costs O(C(n, k) * k). If you need them as masks, Gosper's hack finds the next mask with the same popcount in O(1).

def next_same_popcount(x: int) -> int:
    low = x & -x
    ripple = x + low
    return (((ripple ^ x) >> 2) // low) | ripple


mask, n = 0b0011, 4
while mask < (1 << n):
    print(format(mask, "04b"), end=" ")   # 0011 0101 0110 1001 1010 1100
    mask = next_same_popcount(mask)

Bitmask DP

With 2^n states and n transitions each, a bitmask DP runs in O(2^n * n). When the state is (set, last vertex), as in the traveling salesman problem (Held-Karp), it is O(2^n * n^2) time and O(2^n * n) space. TSP with n = 20 is about 400 million steps: fine in C++, hard in Python. Compared with trying all n! orders, n = 15 means 1.3 trillion versus about 7.4 million.

import math
for n in (10, 15, 20):
    print(n, math.factorial(n), (1 << n) * n * n)

Comparing set representations

RepresentationMembershipUnionMemoryBest for
Integer bitmaskO(1)O(1)w bitsup to 64 items
Bitset (std::bitset, BitSet)O(1)O(n / w)n bitsthousands to millions of items
Hash set (set)O(1) averageO(n)tens of bytes per itemwide, sparse domains
Sorted listO(log n)O(n)one slot per itemwhen order matters

Summary

Bitwise operations are O(1); the cost comes from repetitions and state counts. Subset enumeration is O(2^n * n), all mask/submask pairs are O(3^n), and bitmask DP is typically O(2^n * n) or O(2^n * n^2). These techniques shine when n is around 20 or less; beyond that, look for a different approach.

Questions about this chapter?
Previous chapterImplementationNext chapterPractice Problems

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.