Two's complement converter
-5 in 8 bits is 11111011, the exact pattern a register holds, and 11111011 decodes back to -5. Values that do not fit the width, such as 128 in 8 bits, are rejected instead of wrapping around. Free in your browser.
- Free
- Runs in your browser
- No sign-up
- Your data stays on your device
Run — free
Worked example
- Value
- -5
- Calculation mode
- To binary
- Bits
- 8
- Binary
- 11111011
- Unsigned
- 251
- Min
- -128
- Max
- 127
Two's complement is the standard way modern computers store signed integers in a fixed number of bits. A positive value keeps its ordinary binary form padded on the left to the chosen width; a negative value is stored as the modular wrap of that integer modulo two to the power of the width, so the most significant bit acts as a sign indicator without a separate sign-magnitude field. This converter takes a signed integer and a bit width such as eight, sixteen, or thirty-two and returns the exact bit string a register would hold, or the reverse: a bit pattern and width become the signed decimal value. Overflow outside the legal range for that width is rejected instead of silently wrapping, which keeps homework keys and firmware notes honest.
How two's complement encoding and decoding work
Fix a bit width w at least two. The signed integers that fit are every whole number from negative two to the power of w minus one, through positive two to the power of w minus one, minus one. Zero is all zero bits.
A non-negative value inside the range is written as ordinary base-two digits and zero-padded on the left until there are exactly w bits. A negative value n is encoded as the unique residue of n modulo two to the power of w in that same closed interval of bit patterns: equivalently, invert every bit of the absolute value written in w bits and add one, which is the classic “flip and add one” recipe taught in computer organization courses.
Decoding reverses the map: read the bit string as an unsigned integer u between zero and two to the power of w minus one; if the high bit is clear, the signed value is u; if the high bit is set, the signed value is u minus two to the power of w. Values must stay inside JavaScript’s safe integer range so every digit remains exact when the result is serialized.
Requests that would overflow the chosen width—for example one hundred twenty-eight in eight bits—are rejected with a clear overflow message listing the allowed min and max, rather than wrapping to a wrong negative number that students might trust by accident.
What you can do with it
Homework and CS organization labs
Check encode and decode of signed values at 8/16/32-bit widths, including overflow cases, against a single shared oracle for answer keys.
Firmware and protocol field docs
Document signed register fields and sensor deltas as exact two's-complement bit strings next to decimal values for review and bring-up.
FAQ
What is two's complement?
It is the modular representation of signed integers in a fixed width w: non-negative values use ordinary binary; negatives use (n mod 2^w) so the high bit marks the upper half of the unsigned range. Addition and subtraction then work with the same circuitry as unsigned modular arithmetic.
What range fits in N bits?
Signed two's complement of width w holds integers from −2^(w−1) through 2^(w−1)−1. For example eight bits hold −128 through 127; sixteen bits hold −32768 through 32767.
What happens on overflow?
The converter does not silently wrap, so wrong homework answers and hidden firmware bugs are not papered over.
Can I convert both ways?
Round-tripping a legal value always restores the same integer.
What does it cost?
The browser tool is free and runs locally.
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/fmt/twos-complement \
-H "Authorization: Bearer $KIT_KEY" \
-H "Content-Type: application/json" \
-d '{"mode":"to_binary","bits":8}'const res = await fetch("https://api.kit.forhosting.com/fmt/twos-complement", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.KIT_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"mode": "to_binary",
"bits": 8
})
});
const { task_id } = await res.json();import os, requests
res = requests.post(
"https://api.kit.forhosting.com/fmt/twos-complement",
headers={"Authorization": f"Bearer {os.environ['KIT_KEY']}"},
json={
"mode": "to_binary",
"bits": 8
},
)
task_id = res.json()["task_id"]<?php
$res = file_get_contents("https://api.kit.forhosting.com/fmt/twos-complement", false, stream_context_create([
"http" => [
"method" => "POST",
"header" => "Authorization: Bearer " . getenv("KIT_KEY") . "\r\nContent-Type: application/json",
"content" => '{"mode":"to_binary","bits":8}',
],
]));
$task = json_decode($res, true);body := bytes.NewBufferString(`{"mode":"to_binary","bits":8}`)
req, _ := http.NewRequest("POST", "https://api.kit.forhosting.com/fmt/twos-complement", body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("KIT_KEY"))
req.Header.Set("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)Example request
{
"mode": "to_binary",
"bits": 8
}Example response
{
"task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
"type": "fmt.twos_complement",
"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.
Limits
min_bits | 2 |
max_bits | 64 |
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
Pricing for successful API calls is the published base of $0.002 per item.
How two's complement encoding and decoding work
The algorithm is pure modular integer arithmetic with no floating-point rounding, no random seeds, no wall-clock timestamps, and no network calls, so identical inputs always produce identical JSON.
What you send and what you get back
Classic checks include value negative five with eight bits mapping to one one one one one zero one one, the reverse decode of that pattern back to negative five, and positive forty-two in sixteen bits as a zero-padded pattern. If you only need unsigned decimal-to-binary without a fixed width, use a separate decimal-to-binary landing rather than overloading this two's-complement contract. Send a required mode of either to_binary or from_binary, a required bits field for the word width from two through sixty-four, and either a signed value or a bit string depending on the mode. For to_binary provide value as a JSON integer or a digit string with an optional leading plus or minus; aliases n, number, integer, and signed are accepted. For from_binary provide binary as a string of zeros and ones whose length equals bits; an optional zero-b prefix and internal spaces are stripped. Missing mode or bits, non-integer values, non-binary characters, wrong bit-string length, NaN, Infinity, and overflow outside the two's-complement range for that width fail with invalid_input and are not charged. On success the response echoes mode and bits, the signed value, the exact binary pattern of length bits, the unsigned residue of that pattern, the legal min and max for the width, and method set to twos_complement. Pricing for successful API calls is the published base of $0.002 per item; validation failures do not consume prepaid balance.
Where two's complement converters show up in real work
Computer science and digital design courses introduce two's complement when students first meet signed registers, ALU flags, and the idea that subtraction is addition of the modular inverse; a trusted oracle that returns the exact bit pattern and the legal range speeds answer keys and lab demos without fragile spreadsheet formulas. Embedded firmware and protocol documentation list signed sensor fields, temperature deltas, and offset corrections stored in eight- or sixteen-bit two's complement words next to their hex dumps so reviewers can verify the sign bit at a glance. Compiler and language-runtime notes explain how int8, int16, and int32 map onto machine words; tutors compare student packing code against a known-good bit string for zero, minus one, the minimum negative, and the maximum positive of each width. Because this capability is a pure parse engine, API pricing is the published base of $0.002 per successful item and failed validation does not consume balance. Treat plain unsigned binary strings without a fixed signed width, hex-only dumps, and IEEE floating-point bit patterns as separate search intents with their own landings rather than stretching this signed fixed-width converter past its honest scope.
Integration use cases
Test fixtures for packing code
Generate golden bit patterns and reverse-decode checks for unit tests of int8/int16 serializers without hand-counting bits.