Population count (popcount) calculator
Count how many ones a number has in binary: 42 written in 8 bits is 00101010, with 3 ones at positions 1, 3 and 5 and 5 zeros. Handy for flags, bit masks and Hamming weight homework. Free in your browser.
- Free
- Runs in your browser
- No sign-up
- Your data stays on your device
Run — free
Worked example
- Value
- 42
- Bits
- 8
- Binary
- 00101010
- Popcount
- 3
- Zero bits
- 5
- Set bit indices
- 1, 3, 5
Population count, often shortened to popcount or called Hamming weight, is the number of one-bits in an integer’s binary representation. Developers use it when sizing bitsets, scoring parity-like features without full checksums, estimating set cardinality in bloom-filter style masks, and checking compiler intrinsics such as __builtin_popcount against a reference. This population count calculator accepts a non-negative integer and an optional fixed bit width, returns the zero-padded bit pattern, the total of set bits, how many zeros fill that width, and the least-significant-bit-first indices of every one.
What population count means and why developers ask for it
In computer arithmetic the population count of a non-negative integer is simply how many of its binary digits are one. The same quantity appears under several names: Hamming weight of the bit string, sideway sum, or the result of hardware instructions such as POPCNT on x86 and CNT on ARM. Counting set bits is not the same as converting bases or computing parity alone: conversion tells you the pattern, parity collapses it to even or odd, and popcount reports the full cardinality of the set bits.
That cardinality matters when a flags field packs independent booleans, when a sparse mask represents selected columns in a row store, when a graphics pipeline needs the number of enabled samples, and when interview problems ask for the Hamming distance between two words—which is just the population count of their bitwise XOR.
Where counting set bits really helps
Compiler and language-runtime teams pin __builtin_popcount, Integer.bitCount, and similar intrinsics against a pure reference when validating cross-compilation and WASM shims. Database and search engineers use population count on posting-list bitmaps and roaring-style chunks to estimate selectivity before materializing postings. Security and protocol code counts bits in capability masks and permission bitfields when logging how many privileges a token actually holds.
Classroom platforms and coding-interview sandboxes need a deterministic popcount that shows the padded pattern beside the total so learners can see which positions contribute. Failed validation does not consume balance.
What you can do with it
Intrinsic and unit-test oracles
Compare hardware POPCNT or language bitCount helpers against a pure padded binary and popcount for fixed widths in CI.
Bitset and flags cardinality
Estimate how many flags or bitmap columns are set in a mask before expanding the full list of features.
Teaching Hamming weight
Show students the zero-padded pattern and LSB-first set indices next to the total ones for interview and homework checks.
FAQ
What is population count (popcount)?
Population count is the number of 1-bits in an integer’s binary form—also called Hamming weight. Send value (and optional bits for padding) to receive the count, the padded pattern, and set-bit indices.
Does the calculator accept negative numbers?
No. Value must be a non-negative integer. Two’s-complement interpretations of negatives are out of scope; use a dedicated two’s-complement tool if you need signed widths.
What does the bits parameter control?
Bits fixes the unsigned width used for zero-padding binary and for range checks (1–53). If omitted, width is the natural bit length of value (1 for zero).
How do I get the Hamming distance between two numbers?
Combine the two numbers with a bitwise exclusive or, then count the ones in the result here. Every one marks a position where the numbers differ, so that count is their Hamming distance.
How are the positions of the ones numbered?
From the right, starting at 0 for the least significant bit. That is why 42, written as 00101010 in 8 bits, lists its ones at positions 1, 3 and 5.
Related tools
For developers — API access
Everything on this page is available programmatically. This section is for teams who want to wire it into their own systems; everyone else can just use the tool above.
API endpoint
Prefer to automate it? One authenticated POST creates the task; the result comes back by webhook or a signed link. The same capability also runs here on the web, by email and from Telegram — and soon from our app too.
Call it from your stack
curl -X POST https://api.kit.forhosting.com/dev/population-count \
-H "Authorization: Bearer $KIT_KEY" \
-H "Content-Type: application/json" \
-d '{"value":42}'const res = await fetch("https://api.kit.forhosting.com/dev/population-count", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.KIT_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"value": 42
})
});
const { task_id } = await res.json();import os, requests
res = requests.post(
"https://api.kit.forhosting.com/dev/population-count",
headers={"Authorization": f"Bearer {os.environ['KIT_KEY']}"},
json={
"value": 42
},
)
task_id = res.json()["task_id"]<?php
$res = file_get_contents("https://api.kit.forhosting.com/dev/population-count", false, stream_context_create([
"http" => [
"method" => "POST",
"header" => "Authorization: Bearer " . getenv("KIT_KEY") . "\r\nContent-Type: application/json",
"content" => '{"value":42}',
],
]));
$task = json_decode($res, true);body := bytes.NewBufferString(`{"value":42}`)
req, _ := http.NewRequest("POST", "https://api.kit.forhosting.com/dev/population-count", body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("KIT_KEY"))
req.Header.Set("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)Example request
{
"value": 42
}Example response
{
"task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
"type": "dev.population_count",
"status": "queued",
"_links": {
"result": "/tasks/tsk_…/result"
}
}The API is asynchronous: the call returns a task_id immediately and the result arrives by webhook. Polling is capped at 1 req/s per task.
Pricing
Published price — no tokens, no invented credits. A failed task is never charged.
Errors
| HTTP | Code | Meaning |
|---|---|---|
401 | unauthorized | Missing or invalid API key. |
402 | insufficient_balance | Your balance doesn't cover the task price. |
404 | unknown_type | That task type doesn't exist. |
429 | rate_limited | Too many requests. Use the webhook instead of polling. |
Technical notes
Negative inputs and non-integers fail with invalid_input instead of inventing a two’s-complement interpretation you did not request.
What population count means and why developers ask for it
This endpoint implements a deterministic left-to-right scan over a fixed width so the padded binary string and the list of set indices stay stable across runtimes. Zero has population count zero and a single-bit pattern of zero when no width is forced; the largest safe JavaScript integer still fits in fifty-three bits of significand, which is the upper bound this calculator accepts so every result remains an exact JSON number.
Input contract, padding width, and response fields
Optionally send bits, an integer from one to fifty-three, to fix the unsigned word width used for zero-padding and range checking. When bits is present, value must satisfy zero less than or equal to value and value less than two to the power of bits (capped by the safe-integer limit for wide widths). When bits is omitted, the width defaults to the natural bit length of value—floor of log base two plus one—or one when value is zero, so the binary field is never an empty string. POST a JSON object with value, a required non-negative integer (JSON number or digit string) from zero through Number.MAX_SAFE_INTEGER. On success the body echoes value and bits; binary is the zero-padded bit pattern with the most significant bit on the left; popcount is the Hamming weight; zero_bits is bits minus popcount; set_bit_indices lists every position where a one appears with least significant bit as index zero; and method is the constant population_count for clients that branch on tool identity. Example: value forty-two with bits eight yields binary zero-zero-one-zero-one-zero-one-zero, popcount three, zero_bits five, and set indices one, three, and five. Missing value, negatives, fractions, non-numeric strings, bits outside one through fifty-three, or a value that overflows the chosen width fail with invalid_input and are not billed. Empty objects and arrays are rejected with a short contract message so SDK bugs surface immediately.
Technical questions
How are set_bit_indices ordered?
Indices use least significant bit as position 0 and list every 1-bit from low to high. For example, value 5 (binary 101) yields indices [0, 2].
What does the population count calculator cost?
The browser tool is free. API requests use prepaid KIT balance at $0.002 per successful call; invalid input is not billed.