Skip to content

Try β€œpolymorphism”, β€œTCP handshake” or β€œgit rebase”.

    Computer Basics / How Computers Work

    Everything Is Bytes Plus an Agreement

    Remember the two-switch code from Chapter 1: the same switches meant "meet at park" only because

    Chapter 4 of 912 min read

    The Plain Picture#

    Remember the two-switch code from Chapter 1: the same switches meant "meet at park" only because you and your friend had agreed what each combination means.

    A computer's memory is just a very long row of bytes. The byte 0100 1000 might mean:

    • the number 72, or

    • the letter H, or

    • part of the colour of one dot on the screen, or

    • part of an instruction for the processor.

    The bytes don't know which one they are. The program reading them decides, by following an agreement. The technical word for such an agreement is an encoding or format.

    This chapter covers the agreements you'll meet most as an engineer.

    4.1 Negative Numbers β€” Two's Complement#

    Plain picture#

    Go back to the car odometer from Chapter 2. It shows 00000. Roll it backwards one step: it shows 99999. If everyone agrees "numbers near 99999 actually mean small negative numbers", then 99999 means βˆ’1, 99998 means βˆ’2, and so on.

    Real name#

    Computers do exactly this with bits. The agreement is called two's complement. In it:

    • The leftmost bit tells you the sign: 0 = zero or positive, 1 = negative.

    • 1111 1111 (all ones) means βˆ’1 β€” the "rolled back one step from zero" value.

    Under the hood#

    With 8 bits:

    Output
      0111 1111  =  127    ← biggest positive
      0000 0001  =    1
      0000 0000  =    0
      1111 1111  =   -1
      1111 1110  =   -2
      1000 0000  = -128    ← most negative

    So a signed byte holds βˆ’128 to 127, still 256 values in total β€” just shifted so half are negative.

    How to negate a number: flip every bit, then add 1.

    Output
        5  = 0000 0101
      flip = 1111 1010
      + 1  = 1111 1011  = -5

    Why this agreement won: the processor can use the same adding circuit for positive and negative numbers. Check: 5 + (βˆ’5):

    Output
        0000 0101
      + 1111 1011
      -----------
      1 0000 0000  β†’ the 9th bit falls off β†’ 0000 0000 = 0 βœ”

    Java numbers you will use in DSA#

    Java (the language you will learn in this Java course and use for DSA) has fixed-size whole-number types:

    Java typeBitsRange
    byte8βˆ’128 to 127
    short16βˆ’32,768 to 32,767
    int32βˆ’2,147,483,648 to 2,147,483,647 (about Β±2.1 billion)
    long64about Β±9.2 Γ— 10¹⁸

    The overflow trap (from Chapter 2) in real Java:

    Java
    int big = 2147483647; // Integer.MAX_VALUE, the biggest int
    
    big = big + 1;
    
    System.out.println(big); // prints -2147483648  β€” wrapped to the most negative value!

    This is a classic DSA interview bug. Example: finding the middle of two positions in binary search.

    Java
    int mid = (low + high) / 2; // BUG: low + high can exceed 2.1 billion and wrap negative
    
    int mid = low + (high - low) / 2; // SAFE: high - low never overflows when both are valid positions

    4.2 Decimal Fractions β€” Floating Point#

    Plain picture#

    Write 1 Γ· 3 as a decimal: 0.33333… it never ends. If you only have room for 5 digits you must stop at 0.33333, which is slightly wrong.

    Binary has the same problem, but with different numbers. In binary, 0.1 cannot be written exactly β€” it becomes an endless repeating pattern, just like 1/3 is in decimal.

    Real name#

    Computers store fractions using floating point (the standard is called IEEE 754). The name comes from the decimal point "floating": the number is stored like scientific notation, e.g. 1.5 Γ— 2Β³. Java's double and Python's float both use 64-bit floating point.

    Under the hood#

    A 64-bit float stores three parts:

    Output
      [ 1 bit sign ][ 11 bits exponent ][ 52 bits of digits ("mantissa") ]
           +/βˆ’         how far to shift       the significant digits

    Because only 52 bits of digits fit, 0.1 is stored as the closest possible value, which is very slightly off. Add two slightly-off numbers and the error shows:

    Java
    System.out.println(0.1 + 0.2); // 0.30000000000000004
    
    System.out.println(0.1 + 0.2 == 0.3); // false

    (Python prints exactly the same thing. This is not a Java or Python bug; it's how the hardware stores fractions.)

    Rules that follow from this:

    1. Never compare floats with ==. Check if they are "close enough": Math.abs(a - b) < 1e-9.

    2. Never store money as floating point. Store it as whole numbers of the smallest unit (β‚Ή10.50 β†’ 1050 paise as an integer), or use an exact decimal type (BigDecimal in Java, Decimal in Python, NUMERIC in databases).

    4.3 Text β€” ASCII, Unicode, UTF-8#

    Plain picture#

    Text is stored with a codebook: a list where every character gets a number. "A is 65, B is 66…" Store the numbers, and anyone with the same codebook can read the text back.

    Real names#

    • ASCII (1960s) β€” the first widely used codebook. It covers 128 characters: English letters, digits, punctuation, and invisible control characters like "new line". It needs 7 bits, so each character fits in one byte.

      Output
      'A' = 65 = 0x41       'a' = 97 = 0x61      '0' = 48 = 0x30
      ' ' (space) = 32      '\n' (new line) = 10
    • Unicode β€” one giant codebook for every writing system in the world: Hindi, Chinese, Arabic, emoji, maths symbols… Each character gets a number called a code point, written U+ followed by hex. There are over 150,000 assigned characters.

      Output
      'H'  = U+0048         'Γ©' = U+00E9        'ΰ€•' = U+0915
      '€'  = U+20AC         'πŸ˜€' = U+1F600
    • UTF-8 β€” Unicode says which number each character is. UTF-8 is the agreement for how to turn that number into bytes. It is used by about 98% of websites, and it is the default you should always choose.

    Under the hood β€” how UTF-8 works#

    UTF-8 uses 1 to 4 bytes per character. Small code points use few bytes:

    Output
      code point range        bytes   bit pattern
      ----------------        -----   ---------------------------------------
      U+0000  – U+007F          1     0xxxxxxx
      U+0080  – U+07FF          2     110xxxxx 10xxxxxx
      U+0800  – U+FFFF          3     1110xxxx 10xxxxxx 10xxxxxx
      U+10000 – U+10FFFF        4     11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

    The first byte's leading bits say how many bytes the character uses. The following bytes always start with 10. The x positions hold the code point's bits.

    Two clever consequences:

    1. Every ASCII file is already valid UTF-8, because ASCII characters use the 1-byte form 0xxxxxxx. Old English text needed no conversion.

    2. If you land in the middle of a character, you can tell (bytes starting 10 are never the start), so you can recover.

    Worked example β€” our note Hi πŸ˜€:

    Output
      char   code point   UTF-8 bytes (hex)   byte count
      ----   ----------   -----------------   ----------
      H      U+0048       48                     1
      i      U+0069       69                     1
      space  U+0020       20                     1
      πŸ˜€     U+1F600      F0 9F 98 80            4
                                              -------
                                                7 bytes

    Encoding πŸ˜€ step by step: U+1F600 in binary is 1 1111 0110 0000 0000 (17 bits). It is above U+FFFF, so it uses the 4-byte pattern, which has 3 + 6 + 6 + 6 = 21 x slots. Pad the left with zeros to 21 bits: 000 011111 011000 000000, then drop the four pieces into the slots:

    Output
      11110 000     10 011111     10 011000     10 000000
        F0             9F            98            80

    So the note Hi πŸ˜€ is 4 characters but 7 bytes. Characters and bytes are not the same thing.

    4.4 Images and Colours#

    A picture on a screen is a grid of tiny dots called pixels. Each pixel is a colour, stored as 3 bytes (red, green, blue β€” Chapter 3).

    A 1920 Γ— 1080 screen has about 2 million pixels. At 3 bytes each, one uncompressed frame is about 6 MB. That is why image formats like PNG and JPEG exist: they compress the data (store it in fewer bytes) by describing patterns instead of every pixel.

    Gotchas

    • "Length of a string" is ambiguous. Characters? Bytes? Something else? Java stores text in UTF-16 (2 bytes per unit, 4 for emoji), so in Java "πŸ˜€".length() is 2, not 1. Python's len("πŸ˜€") is 1 (it counts code points), but len("πŸ˜€".encode("utf-8")) is 4 (bytes). Databases limit column sizes in bytes or characters depending on settings β€” check which.

    • Mojibake (garbled text like é instead of Γ©) happens when bytes written with one encoding are read with another. Fix: use UTF-8 everywhere, and say so explicitly (files, databases, HTTP headers).

    • Integer overflow is silent in Java. When a sum might pass ~2.1 billion, use long.

    Check yourself

    5 questions
    1

    In 8-bit two's complement, what number is 1111 1110?

    Show answer

    βˆ’2. (Flip 1111 1110 β†’ 0000 0001, add 1 β†’ 0000 0010 = 2, so it's βˆ’2.)

    2

    Why does 0.1 + 0.2 == 0.3 print false?

    Show answer

    0.1 and 0.2 can't be stored exactly in binary floating point; their tiny errors add up to a value slightly above 0.3.

    3

    How would you store the price β‚Ή499.99 in a database, and why?

    Show answer

    As an integer number of paise (49999) or as an exact decimal type β€” floating point would add rounding errors to money.

    4

    How many bytes does the word cafΓ© take in UTF-8?

    Show answer

    5 bytes: c, a, f are 1 byte each; Γ© (U+00E9) is 2 bytes (C3 A9).

    5

    In Java, why is (low + high) / 2 dangerous?

    Show answer

    If low + high is bigger than 2,147,483,647, it overflows and becomes negative. Use low + (high - low) / 2.