ForHosting KIT · Math

Two's complement

In 8 bits, −5 becomes 11111011 and +5 becomes 00000101. Enter a signed whole number and a word width from 2 to 64 bits and get its exact two's complement pattern; values that do not fit are refused, never wrapped. Free in your browser.

  • Free
  • Runs in your browser
  • No sign-up
  • Your data stays on your device
Use it from WebAPIEmailTelegramApp soon
If you enter
Value
-5
Bits
8
You get
Binary
11111011
Unsigned
251
Min
-128
Max
127

Two's complement is the representation modern processors use for signed integers: a fixed-width bit string whose high bit is the sign and whose remaining bits complete a modular encoding of the value. This two's complement calculator accepts a signed integer and a bit width, then returns the exact binary word for that width. Non-negative values become the ordinary magnitude bits padded with leading zeros. Negative values become the residue of the integer modulo two to the power of the width, which is the familiar invert-and-add-one construction taught in every computer-organization course.

What two's complement means and how the bits are produced

Two's complement is the representation almost every CPU uses for signed integers. For a word of width w bits the representable range is the closed interval from minus two to the power of w minus one through two to the power of w minus one minus one. The most significant bit is the sign bit: zero means a non-negative value stored as the ordinary unsigned binary of that magnitude, padded on the left with zeros to exactly w characters.

A one in the sign bit means a negative value. Encoding a negative integer n is the same as taking the mathematical residue of n modulo two to the power of w: invert every bit of the positive magnitude and add one, then keep exactly w bits. That modular view is why subtracting one from zero yields a string of ones, which decodes as minus one, and why the most negative value in w bits is a one followed by w minus one zeros.

This calculator implements that identity with BigInt modular arithmetic so every bit is exact for widths from two through sixty-four. Positive five in eight bits is 00000101; negative five in eight bits is 11111011; zero is a string of zeros; minus one is a string of ones. Those four landmarks are enough to verify any later width by the same modular rule.

Where a two's complement encoder earns its keep

Classrooms use a two's complement calculator so learners can convert signed homework values to eight-bit and sixteen-bit words without flipping a sign bit by hand and missing the plus-one step that distinguishes two's complement from ones' complement. Exam generators need a deterministic oracle that rejects one hundred twenty-eight in eight bits as overflow rather than wrapping to minus one hundred twenty-eight, because wrapping is a hardware behaviour students must recognise as distinct from a legal encoding of the original integer.

Embedded and firmware reviews often need a quick check that a documented constant really occupies the advertised field width before it is packed into a register, a protocol word, or a bitfield in a datasheet. Protocol designers compare the returned word against a packet dump when a signed field is transmitted most-significant-bit first. Keep requests small, assert the binary field in tests, and you get reproducible two's-complement words for homework, labs, and edge workers without standing up a full assembler toolchain of your own.

Classroom and homework checks

Convert signed worksheet values to eight-bit or sixteen-bit two's-complement words and confirm the invert-and-add-one result without a hand-drawn bit table.

Firmware and protocol reviews

Check that a documented signed constant actually fits the advertised field width before packing it into a register or a wire format.

How do I convert a signed integer to two's complement binary?

Send the integer as value and the word width as bits (2–64).

What happens if the integer does not fit in the bit width?

For eight bits the legal range is −128 through 127, so 128 is an error rather than the bit pattern of −128.

How is a negative value encoded?

As the non-negative residue of the integer modulo 2^w, which is the same as inverting the magnitude bits and adding one. Minus five in eight bits is 11111011.

Which bit widths are supported?

Any integer width from 2 to 64. Typical teaching and firmware widths are 8, 16, 32, and 64, provided the value stays inside JavaScript's safe integer range.

What is the difference between ones' complement and two's complement?

Ones' complement only inverts every bit of the positive value; two's complement inverts and then adds one. That extra step is what turns −5 into 11111011 in 8 bits and makes −1 a row of ones.

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.

POSThttps://api.kit.forhosting.com/math/twos-complement

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.

curl -X POST https://api.kit.forhosting.com/math/twos-complement \
  -H "Authorization: Bearer $KIT_KEY" \
  -H "Content-Type: application/json" \
  -d '{"value":-5,"bits":8}'
{
  "value": -5,
  "bits": 8
}
{
  "task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
  "type": "math.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.

Per request$0.002

Published price — no tokens, no invented credits. A failed task is never charged.

min_bits2
max_bits64
HTTPCodeMeaning
401unauthorizedMissing or invalid API key.
402insufficient_balanceYour balance doesn't cover the task price.
404unknown_typeThat task type doesn't exist.
429rate_limitedToo many requests. Use the webhook instead of polling.

If the integer does not fit in the signed range of the chosen width the task fails with invalid_input instead of wrapping in silence. Successful API calls cost $0.002; invalid input is not billed.

What two's complement means and how the bits are produced

It does not wrap overflowing values the way a hardware register would: if the signed integer cannot live in the chosen width the request fails instead of quietly producing a wrong word that belongs to a different integer. Students can therefore check homework against a definition that matches textbooks and hardware manuals, and automation can trust that a success payload is a legal encoding for the stated width rather than a wrapped residue that happens to look binary.

Input contract, legal range, and how overflow is reported

The field value is the signed integer to encode. Fractions, scientific notation, empty strings, Infinity, and NaN are rejected so a bad spreadsheet cell cannot become a wrong bit pattern. The field bits is the word width as an integer from two to sixty-four inclusive, which covers the common int8, int16, int32, and int64 teaching widths while remaining cheap to compute on the edge. Example: value minus five and bits eight produce binary 11111011, unsigned two hundred fifty-one, min minus one hundred twenty-eight, and max one hundred twenty-seven. Missing fields, non-integers, and a bits value outside two through sixty-four fail the same way and are not billed. Send a JSON object with two required fields. It may be a JSON number or a decimal digit string with an optional leading plus or minus sign. The absolute value must stay inside JavaScript's safe integer range so the echoed value remains an exact JSON number. Aliases n, integer, and number are accepted for value; aliases width, bit_width, and nbits are accepted for bits. On success the response echoes value and bits, returns binary as a string of exactly bits characters each zero or one, returns unsigned as the same bit pattern interpreted as a non-negative integer, and returns min and max so callers can display the legal range next to the answer. The contract is deliberately fail-closed: wrapping 128 to 10000000 would be a correct encoding of minus one hundred twenty-eight, not of one hundred twenty-eight, and this endpoint refuses to blur that distinction.

Where a two's complement encoder earns its keep

Successful API calls cost the published $0.002; validation failures do not consume balance; nothing is stored after the response returns.

Exam and LMS auto-grading

Mark two's-complement items with a deterministic oracle that rejects overflow as invalid_input instead of wrapping the integer into a different value.

What does the two's complement calculator cost?

The browser tool is free. API requests use prepaid KIT balance at $0.002 per successful call; invalid input is not billed.

Read the full KIT documentation →