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 · 2/6

How It Works

This chapter traces small examples by hand to show why the classic tricks work: the lowest set bit x & -x, clearing it with x & (x - 1), popcount, subset enumeration with bitmasks, submask enumeration, a first look at bitmask DP, and XOR tricks.

x & -x: the lowest set bit

Take x = 12, or 00001100 in 8 bits. Since -x is ~x + 1:

StepValueBits
x1200001100
~x-1311110011
~x + 1 = -x-1211110100
x & -x400000100

In ~x, every bit below the lowest set bit of x becomes 1. Adding 1 carries through them and stops exactly at that position. So x and -x share that one bit, disagree on everything above it, and are both 0 below it; the AND keeps only that bit. A Fenwick tree uses this to jump between ranges.

x & (x - 1): clearing the lowest set bit

Subtracting 1 turns the lowest set bit into 0 and every bit below it into 1. For 12 = 1100, 11 = 1011, and the AND is 1000 = 8. Two tools follow at once:

  • Power-of-two test: x > 0 and (x & (x - 1)) == 0
  • Counting set bits (Brian Kernighan's method): the number of clears until x reaches 0 is the popcount.

Tracing popcount for x = 13 (1101):

Roundxx - 1x & (x - 1)Count
11101110011001
21100101110002
31000011100003

The loop runs once per set bit, so sparse numbers finish quickly.

def popcount(x: int) -> int:
    count = 0
    while x:
        x &= x - 1
        count += 1
    return count

print(popcount(13), popcount(255), (13).bit_count())  # 3 8 3

Enumerating subsets with a bitmask

A set of n items such as ["a", "b", "c"] has 2^n = 8 subsets, one for each integer from 0 to 7. If bit i of the mask is 1, item i is in the subset.

maskbinarypopcountsubset
00000{}
10011{a}
20101{b}
30112{a, b}
41001{c}
51012{a, c}
61102{b, c}
71113{a, b, c}
items = ["a", "b", "c"]
n = len(items)
for mask in range(1 << n):
    chosen = [items[i] for i in range(n) if (mask >> i) & 1]
    print(format(mask, "03b"), chosen)

Set algebra becomes integer arithmetic: union is OR, intersection is &, difference is a & ~b, membership is (a >> i) & 1.

Enumerating submasks

To visit only the subsets of a given mask, repeat sub = (sub - 1) & mask. For mask = 1011 the walk is 1011, 1010, 1001, 1000, 0011, 0010, 0001, then 0. Subtracting 1 turns the low bits on and the AND removes anything outside the mask, so each step moves to the next smaller number made only of the mask's bits.

mask = 0b1011
sub = mask
while True:
    print(format(sub, "04b"))
    if sub == 0:
        break
    sub = (sub - 1) & mask

A first look at bitmask DP

When a DP state contains "the set of items used so far", encode that set as an integer and use it as an array index. To assign n jobs to n workers at minimum total cost, let dp[mask] be the cheapest way to give the jobs in mask to the first popcount(mask) workers. The next worker is determined by popcount(mask), so there are only 2^n states, each trying at most n jobs: O(2^n * n) overall. The practice chapter builds a full example.

XOR tricks

XOR satisfies a ^ a == 0 and a ^ 0 == a, and it is commutative and associative. XOR together a list where every value appears twice except one, and the pairs cancel: 4 ^ 1 ^ 2 ^ 1 ^ 2 = 4.

from functools import reduce

print(reduce(lambda a, b: a ^ b, [4, 1, 2, 1, 2]))   # 4
a, b = 0b1100, 0b1010
print(bin(a ^ b), (a ^ b).bit_count())              # 0b110 2: Hamming distance

Summary

x & -x isolates the lowest set bit and x & (x - 1) removes it. The integers 0 to 2^n - 1 are exactly the subsets of n items, and (sub - 1) & mask walks down through submasks. These few moves are the foundation of bitmask DP and XOR puzzles.

Questions about this chapter?
Previous chapterConceptsNext chapterImplementation

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.