Number Representation and Digital Logic

Understand binary, hex, two's complement, floating point and the logic gates and circuits that computers are built from.

Beginner · about 5 hours · difficulty 2/5

Learn first: Bit Manipulation

This topic appears in aptitude-style CS MCQs and explains several bugs you will meet in DSA, such as overflow and floating point comparison errors. It pairs well with bit manipulation.

Number representation

  • Convert between binary, octal, decimal and hexadecimal quickly. One hex digit is exactly four bits.
  • Two's complement represents negative integers: invert the bits and add one. An n-bit signed integer ranges from -2^(n-1) to 2^(n-1) - 1, which is why INT_MIN has no positive counterpart and abs(INT_MIN) overflows.
  • Overflow: adding two large positives can wrap to a negative in fixed-width arithmetic.
  • IEEE 754 floating point: sign, exponent and mantissa. Many decimals (like 0.1) cannot be represented exactly, so never compare floats with ==; compare with a small epsilon. Know what NaN and infinity are.
  • Endianness: little-endian stores the least significant byte first (x86), big-endian the most significant first (network byte order).
  • Character encodings: ASCII and UTF-8 basics.

Digital logic

  • Gates: AND, OR, NOT, NAND, NOR, XOR. NAND and NOR are universal.
  • Boolean algebra, De Morgan's laws, and simplifying with Karnaugh maps.
  • Combinational circuits: half and full adders, multiplexers, decoders.
  • Sequential circuits: latches and flip-flops (SR, D, JK, T) store state; registers and counters are built from them.

Good enough to move on: you can convert -13 to 8-bit two's complement, explain why 0.1 + 0.2 != 0.3 in most languages, and build a full adder from gates on paper.

Key concepts

  • Binary, octal and hex conversion
  • Two's complement and overflow
  • IEEE 754 floating point
  • Endianness
  • Logic gates and Boolean algebra
  • Karnaugh maps
  • Adders and multiplexers
  • Flip-flops and registers

Mini project

Write a small program that prints the binary, hex, two's complement and IEEE 754 bit layout of any integer or float you enter, and use it to show overflow at INT_MAX + 1 and the exact stored value of 0.1.

Check yourself

Why does abs(INT_MIN) overflow in a 32-bit signed integer, and what value does it usually return?

Free resources