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, orpart 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:
0111 1111 = 127 β biggest positive
0000 0001 = 1
0000 0000 = 0
1111 1111 = -1
1111 1110 = -2
1000 0000 = -128 β most negativeSo 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.
5 = 0000 0101
flip = 1111 1010
+ 1 = 1111 1011 = -5Why this agreement won: the processor can use the same adding circuit for positive and negative numbers. Check: 5 + (β5):
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 type | Bits | Range |
|---|---|---|
byte | 8 | β128 to 127 |
short | 16 | β32,768 to 32,767 |
int | 32 | β2,147,483,648 to 2,147,483,647 (about Β±2.1 billion) |
long | 64 | about Β±9.2 Γ 10ΒΉβΈ |
The overflow trap (from Chapter 2) in real 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.
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 positions4.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:
[ 1 bit sign ][ 11 bits exponent ][ 52 bits of digits ("mantissa") ]
+/β how far to shift the significant digitsBecause 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:
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:
Never compare floats with
==. Check if they are "close enough":Math.abs(a - b) < 1e-9.Never store money as floating point. Store it as whole numbers of the smallest unit (βΉ10.50 β
1050paise as an integer), or use an exact decimal type (BigDecimalin Java,Decimalin Python,NUMERICin 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) = 10Unicode β 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+1F600UTF-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:
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 10xxxxxxThe 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:
Every ASCII file is already valid UTF-8, because ASCII characters use the 1-byte form
0xxxxxxx. Old English text needed no conversion.If you land in the middle of a character, you can tell (bytes starting
10are never the start), so you can recover.
Worked example β our note Hi π:
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 bytesEncoding π 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:
11110 000 10 011111 10 011000 10 000000
F0 9F 98 80So 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'slen("π")is 1 (it counts code points), butlen("π".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 questionsIn 8-bit two's complement, what number is 1111 1110?
Show answerHide answer
β2. (Flip 1111 1110 β 0000 0001, add 1 β 0000 0010 = 2, so it's β2.)
Why does 0.1 + 0.2 == 0.3 print false?
Show answerHide 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.
How would you store the price βΉ499.99 in a database, and why?
Show answerHide answer
As an integer number of paise (49999) or as an exact decimal type β floating point would add rounding errors to money.
How many bytes does the word cafΓ© take in UTF-8?
Show answerHide answer
5 bytes: c, a, f are 1 byte each; Γ© (U+00E9) is 2 bytes (C3 A9).
In Java, why is (low + high) / 2 dangerous?
Show answerHide answer
If low + high is bigger than 2,147,483,647, it overflows and becomes negative. Use
low + (high - low) / 2.