flashman
← All guides

Two's complement, bit width, and signed integer boundaries

Interpret signed integers correctly by defining bit width, two's complement ranges, sign extension, byte order, overflow behavior, transport types, and fixtures.

2026-09-06 · 8 min read

  • binary
  • integers
  • data-formats

A string of binary or hexadecimal digits has no inherent signedness. Under an eight-bit unsigned interpretation FF is 255; under eight-bit two's complement it is -1. Changing the width changes where the sign boundary lies.

Correct conversion therefore starts with a field contract: bit width, signedness, byte order, scaling or unit, and behavior when a value exceeds the representable range.

Derive the fixed-width range

An n-bit two's complement integer represents values from negative two raised to n minus one through positive two raised to n minus one minus one. The highest bit contributes to the negative interpretation within that width.

  • Eight-bit signed values range from -128 through 127.
  • Sixteen-bit signed values range from -32768 through 32767.
  • All one bits represent -1 at any fixed two's complement width.
  • Leading zeroes can be significant documentation of field width.

Separate sign extension from byte order

When widening a signed two's complement value, repeat the sign bit into the new high bits. Zero extension is appropriate for an unsigned value. Narrowing discards high bits and must be range-checked before conversion.

Endianness controls the order of bytes in storage or transmission; it does not reverse bits inside each byte and does not itself determine signedness. Write protocol examples as both ordered bytes and the resulting number.

Protect language and JSON boundaries

Language runtimes differ in default integer widths, overflow behavior, shift operators, and arbitrary-precision support. Parse into a type wide enough to inspect the complete source before applying the intended mask and signed interpretation.

  • Reject overflow unless modular wrapping is explicitly required.
  • Avoid floating-point JSON numbers for integers beyond the consumer's exact range.
  • Use decimal or hexadecimal strings when width must be preserved.
  • Document units and scaling separately from bit representation.

Build boundary fixtures

Use Flashman's number base converter to inspect unsigned digits, units converter for bit and byte context, hash to identify public binary fixtures, diff to compare padded representations, and JSON formatter for transport examples. Apply signed interpretation using the documented width.

Test zero, one, -1, maximum positive, minimum negative, values on both sides of the sign bit, widening, narrowing, both byte orders, malformed lengths, overflow, and every supported language binding.

Try these tools