- Learn
- Computer Science & IT
- Computer Science
- Introduction to Computer Science
- Binary and Data Representation
Binary and Data Representation
BeginnerLesson 2 of 7 in Introduction to Computer Science Course
What you will learn
- Explain how groups of bits encode information, and convert whole numbers between decimal, binary and hexadecimal.
- Explain bits, bytes and how many values a group of bits can holdDescribe bits and bytes, work out how many patterns a number of bits gives, and read storage and speed units correctly.
- Convert whole numbers between decimal and binaryUse place values to read binary numbers, and convert decimal whole numbers to binary with two reliable methods.
- Use hexadecimal as a shorthand for binaryConvert between hexadecimal, binary and decimal, and explain why programmers write bytes, colors and addresses in hexadecimal.
- Explain bits, bytes and how many values a group of bits can hold
- Store non-negative and negative integers in a fixed number of bits, work out their ranges, and explain what happens when a value does not fit.
- Store unsigned integers and recognize their rangeRepresent non-negative whole numbers in a fixed width, choose a width that fits the values, and explain overflow.
- Represent negative integers in two's complementRead and write negative whole numbers in two's complement, find the range of a signed width, and compare it with sign-magnitude.
- Store unsigned integers and recognize their range
- Write fractions in binary, encode and decode numbers in the IEEE 754 floating-point formats, and explain the limits on their range and precision.
- Write fractions in binary and see why some cannot be exactConvert between decimal and binary fractions, recognize repeating binary fractions such as 0.1, and describe fixed-point numbers.
- Encode and decode IEEE 754 floating-point numbersUse binary scientific notation and the sign, exponent and fraction fields of the IEEE 754 single- and double-precision formats.
- Explain range, precision and rounding error in floating pointExplain why floating-point values are approximations, predict typical effects such as 0.1 + 0.2, and choose a suitable number type.
- Write fractions in binary and see why some cannot be exact
- Explain how characters become numbers and bytes, use ASCII and Unicode, and predict how many bytes UTF-8 text takes.
- Encode text with character codes and ASCIIUse a character code table to turn text into numbers and bits, read the layout of ASCII, and explain its limits.
- Use Unicode code points and UTF-8 encodingDistinguish a Unicode code point from its encoded bytes, encode characters in UTF-8, and explain garbled text and byte counts.
- Encode text with character codes and ASCII
- Describe how pictures become pixels and color values, calculate the storage they need, and explain how sound is sampled into numbers.
- Represent images with pixels and color valuesDescribe bitmap images, color depth, RGB and hex color codes, palettes and transparency.
- Calculate image sizes and compare bitmap with vector graphicsCalculate the storage an uncompressed image or video needs, explain what files add, and describe vector graphics.
- Digitize sound by sampling and quantizingExplain sampling, sample rate and bit depth, apply the sampling rule, and calculate the size of uncompressed audio.
- Represent images with pixels and color values
- Explain how compression makes data smaller, apply simple lossless methods, and choose between lossless and lossy formats.
- Explain lossless compression with run-length and other codesApply run-length encoding and variable-length codes, describe dictionary methods, and explain why no method shrinks every file.
- Explain lossy compression and choose a suitable formatDescribe how lossy compression discards less noticeable detail, weigh quality against size, and choose formats for different kinds of data.
- Explain lossless compression with run-length and other codes
Binary and Data Representation study guide
1Count patterns and change number bases
A computer can use the same group of bits for a number, a letter, or part of a picture. The interpretation gives the pattern its meaning. Before working with those interpretations, you need to count the patterns available and read the units used for storage and transfer. Decimal, binary, and hexadecimal then give you three ways to write a whole number, each with place values that make conversions predictable.
1.1 Bits, bytes, and storage units
A bit, short for binary digit, has one of two values: 0 or 1. Hardware can distinguish two physical states reliably, such as high and low voltage, opposite directions of magnetization, or light and no light. The written digits describe those states; they need not literally appear inside a device.
Count the patterns
Each new bit doubles the choices. Two bits have four patterns: 00, 01, 10, and 11. Three bits have eight. In general, bits give patterns. A nibble is 4 bits, and a byte is 8 bits, so a byte has 256 patterns. A byte is also the smallest addressable unit of memory on most modern computers.
To encode a set of values, choose enough patterns for every member. For 26 letters, four bits give only 16 patterns; five bits give 32, so five bits suffice. For 1,000 values, nine bits give 512 and ten give 1,024. Unused patterns are allowed. With 16 bits there are 65,536 patterns, and with 32 there are 4,294,967,296.
The pattern count differs from the largest unsigned number. Four bits provide 16 patterns, but counting starts at zero, so the values run from 0 through 15. One pattern is already used for zero.
To find the minimum width systematically, compare successive powers of two with the required number of choices. Stop at the first power that is large enough. The test is for N distinct values. Exact equality is allowed: eight choices fit in three bits, while a ninth choice needs a fourth bit. A larger width still works, but it is no longer the minimum.
Give the pattern a meaning
The byte 01000001 can mean the integer 65, the ASCII letter "A", or a color-channel intensity of 65 on a 0–255 scale. The bits alone do not select one reading. A program's data type and the file's format determine how to interpret them.
Read storage units
Two families of prefixes are common:
| Decimal storage | Bytes | Binary storage | Bytes |
|---|---|---|---|
| 1 kB | 1,000 | 1 KiB | 1,024 |
| 1 MB | 1,000,000 | 1 MiB | 1,048,576 |
| 1 GB | 1,000,000,000 | 1 GiB | 1,073,741,824 |
The decimal prefixes are SI prefixes; the binary prefixes are IEC prefixes. In each decimal step the unit grows by 1,000; in each binary step it grows by 1,024. To express bytes in a larger unit, divide by the number of bytes in that unit.
A drive labeled 500 GB contains 500,000,000,000 bytes. Dividing by 1,073,741,824 gives about 465.66 GiB. Software may label that binary quantity "GB", which makes the displayed capacity look smaller. The unit change itself has removed no bytes; formatting and system files are separate matters.
Distinguish bits from bytes
Lowercase b means bit; uppercase B means byte. A 100 Mbit/s connection transfers at most 100 million bits each second. Dividing by 8 gives 12.5 million bytes per second, or 12.5 MB/s, before protocol overhead. Reading that speed as 100 MB/s makes it eight times too large.
Key Takeaways
- A byte has 8 bits; a nibble has 4.
- Each additional bit doubles the pattern count.
- Choose the smallest bit count for which the available patterns cover every value.
- A data type or encoding gives a bit pattern its meaning.
- SI storage prefixes use powers of 10; IEC prefixes use powers of 2.
- Divide a bit rate by 8 to obtain the corresponding byte rate.
1.2 Binary place value and conversion
Binary is a positional number system: a digit's value depends on where it sits. Decimal uses ten digits and powers of 10. Binary uses two digits, 0 and 1, and powers of 2. Reading a binary number is a matter of adding the places that contain a 1.
Read a binary whole number
From right to left, the places are 1, 2, 4, 8, 16, 32, 64, 128, and so on. Each is twice the previous one because , , and .
For , line up the six bits with their places:
| Place | 32 | 16 | 8 | 4 | 2 | 1 |
|---|---|---|---|---|---|---|
| Bit | 1 | 0 | 1 | 1 | 0 | 1 |
The value is . A zero contributes nothing, but it keeps the other digits in the right places. Leading zeros leave the value unchanged: 00101101 is also 45.
The leftmost bit is the most significant bit, or MSB. The rightmost is the least significant bit, or LSB. Every place except the last is even, so a binary whole number is odd exactly when its LSB is 1.
Convert by subtracting powers of two
To write 156 in binary, start with the largest power of two that fits: 128. Subtract it, leaving 28. The 64 and 32 places do not fit, so both receive 0. Take 16, leaving 12; take 8, leaving 4; take 4, leaving 0. The unused 2 and 1 places receive 0.
In place order, the result is . Check by adding the chosen places: . Skipping an unused column would move every later bit and change the number.
The subtraction method works because each binary place can be used at most once. After taking the largest fitting power, the remainder is smaller than that power. Continue downward through every place, including the zero places, until the ones place is filled. This makes the chosen bits line up with distinct powers instead of a list of powers without positions.
Convert by repeated division
Another method divides by 2 repeatedly. Keep the quotient for the next division and record the remainder:
| Number | Quotient | Remainder |
|---|---|---|
| 156 | 78 | 0 |
| 78 | 39 | 0 |
| 39 | 19 | 1 |
| 19 | 9 | 1 |
| 9 | 4 | 1 |
| 4 | 2 | 0 |
| 2 | 1 | 0 |
| 1 | 0 | 1 |
Read the remainders from bottom to top, giving 10011100. The first remainder belongs to the ones place, so reading downward reverses the place order. Here that would produce 00111001, which is 57.
Keep the base visible
The subscript in means base 2, so its value is two. The same digits in mean ten. Binary is usually read digit by digit: "one zero". Counting proceeds 0, 1, 10, 11, 100, 101, 110, 111, 1000; a column carries when it reaches 2. A string of eight ones is . Appending a zero shifts every place left and doubles the value: 101 becomes 1010, taking five to ten.
Key Takeaways
- Add the powers of two whose bits are 1.
- Leading zeros preserve a value; missing internal places do not.
- Read repeated-division remainders from last to first.
- A whole number is odd exactly when its least significant bit is 1.
- Appending a zero doubles an unbounded binary whole number.
1.3 Hexadecimal as readable binary
Hexadecimal, or hex, writes numbers in base 16. Its digits are 0–9 followed by A, B, C, D, E, and F, which mean 10 through 15. A single hex digit can describe every possible group of four bits, making long binary patterns easier to read.
Match four bits to one digit
Because , each hex place corresponds to exactly four binary places:
| Hex | Binary | Hex | Binary |
|---|---|---|---|
| 0 | 0000 | 8 | 1000 |
| 1 | 0001 | 9 | 1001 |
| 2 | 0010 | A | 1010 |
| 3 | 0011 | B | 1011 |
| 4 | 0100 | C | 1100 |
| 5 | 0101 | D | 1101 |
| 6 | 0110 | E | 1110 |
| 7 | 0111 | F | 1111 |
For binary to hex, group from the right. The pattern 10011100 becomes 1001 1100, or 0x9C. For a shorter final group on the left, add leading zeros: 101101 becomes 0010 1101, or 0x2D. Grouping it from the left as 1011 01 would put the digits in the wrong places.
To go back, expand every digit to four bits. Thus 0x3E8 becomes 0011 1110 1000. Keep all four bits inside each group, even when a group begins with zeros. Only zeros at the far left of the whole number can be dropped without changing its value.
Use base-16 place values
From right to left, hex places are 1, 16, 256, and 4,096. Multiply each digit's value by its place, then add. For 0x2F, the calculation is . For 0x3E8:
Decimal to hex also works by repeated division, now by 16. For 1,000, the first quotient is 62 with remainder 8. Dividing 62 gives quotient 3 with remainder 14, written E. Dividing 3 gives quotient 0 with remainder 3. Read the remainders upward: 3, E, 8.
The grouping works through place value, not just a matching table. In a two-digit hex number, the left nibble contributes its value times 16, and the right nibble contributes its value times 1. In binary, shifting a nibble four places left also multiplies its value by 16. That shared factor lets the two groups be read independently without converting the whole number to decimal first.
Recognize common uses
One byte is two nibbles, so it is exactly two hex digits, from 0x00 to 0xFF. A byte viewer can show a long file four times more compactly in hex than in binary while keeping the group boundaries visible.
Web colors such as #FF8000 use pairs of hex digits for red, green, and blue. Memory addresses and Unicode code points such as U+00E9 also use hex. A MAC address such as 3C:22:FB:9A:01:7E writes six bytes as twelve hex digits, with separators between the bytes.
The prefix 0x, a base subscript such as , or the # in a color code identifies the notation. The computer stores the same bits whichever notation a person uses. In particular, 0x10 means sixteen. The value fifteen is the single digit F; writing "15" occupies two hex places and means twenty-one.
Key Takeaways
- Hex uses 0–9 and A–F, with A–F representing 10–15.
- Group binary from the right in fours to convert to hex.
- One byte is exactly two hex digits.
- Hex place values are powers of 16; changing notation does not change the stored bits.
2Store whole numbers in a fixed width
A fixed number of bits can hold only a fixed set of whole numbers. The chosen interpretation decides whether all those patterns represent nonnegative values or whether some represent negative values. You will read the same byte both ways, choose widths that fit a required range, and follow what happens at the endpoints. Two's complement also explains how negative values keep their meaning when their width grows.
2.1 Unsigned values and overflow
An unsigned integer represents a nonnegative whole number. All its bits have ordinary positive binary weights. The width fixes how many places are available, so a byte cannot grow a ninth bit just because a result needs one.
Find the range
For bits, there are patterns. Starting at zero gives the range . The largest value has a 1 in every place:
| Width | Unsigned range |
|---|---|
| 8 bits | 0–255 |
| 16 bits | 0–65,535 |
| 32 bits | 0–4,294,967,295 |
The number of available values and the maximum value differ by one. Eight bits allow 256 choices, but 256 itself needs nine places, 1 0000 0000.
A stored value fills its width with leading zeros. For example, 45 in 16 bits is 0000000000101101, or 0x002D. Those zeros identify the width without changing the value. A negative number has no unsigned representation, whatever width you choose.
Choose enough places
An age range of 0 through 150 fits in 8 bits because 150 is below 255. A count from 0 through 100,000 contains 100,001 possible values. Sixteen bits offer only 65,536 patterns. Seventeen offer 131,072, so 17 is the minimum mathematical width. A program using common widths of 8, 16, 32, and 64 would choose 32 bits.
The same reasoning applies to any bounded counter: check the largest value the counter must actually hold, including both endpoints. A range of 0 through 256 needs 257 patterns and therefore will not fit in one byte.
A useful boundary check compares adjacent widths. The unsigned maximum for 8 bits is 255, and for 9 bits it is 511. Adding a bit doubles the number of patterns; the maximum becomes twice the old maximum plus one. This distinction matters when a requirement lands exactly on a power of two: that endpoint needs a new place even though the previous width has that many patterns.
Follow a result beyond the range
Overflow means that a result does not fit the chosen representation. If an 8-bit calculation keeps only the lowest eight bits, 255 plus 1 produces 1 0000 0000 and stores 00000000: zero. The extra place is discarded.
For 200 plus 100, the mathematical result is 300. The width keeps the remainder after a full cycle of 256 patterns: . The stored byte is 00101100. This behavior is called wraparound. It does not change the arithmetic fact that 200 plus 100 is 300; it describes what the limited storage retains.
Overflow behavior depends on the system. Some operations wrap, some signal an error, and some number types grow. A calculation asking about wraparound must identify that behavior before you discard high bits.
See fixed widths in data
An IPv4 address has 32 bits, giving about 4.3 billion possible patterns. That finite address space helped drive the need for a larger addressing system. An ordinary RGB color channel has 8 bits, which explains its 0–255 intensity scale. The maximum in both cases follows from the width; a longer decimal spelling adds no storage capacity.
Key Takeaways
- An unsigned n-bit integer ranges from 0 to 2ⁿ − 1.
- Count both endpoints when selecting a width.
- Leading zeros fill a width without changing an unsigned value.
- Overflow means a result falls outside the representable range.
- When a system keeps only the low n bits, unsigned values wrap in cycles of 2ⁿ.
2.2 Negative integers in two's complement
A negative integer needs a representation rule, not just a minus sign written beside a byte. Two's complement gives the top bit a negative weight. The remaining places keep their positive weights, so every pattern has one signed value and zero has one pattern.
Compare two signed readings
A simpler scheme, sign-magnitude, uses the top bit only for the sign and the remaining bits for the size. In 8 bits, +5 is 00000101 and −5 is 10000101. It has two zeros, 00000000 and 10000000, and mixed-sign addition needs extra rules.
In 8-bit two's complement, the weights are −128, 64, 32, 16, 8, 4, 2, and 1. Thus 11010011 means . Reading the other seven bits as a magnitude of 83 would give −83, which belongs to a different representation.
| Width | Two's complement range |
|---|---|
| 8 bits | −128–127 |
| 16 bits | −32,768–32,767 |
| 32 bits | −2,147,483,648–2,147,483,647 |
In general the range is . Zero and positive values look like ordinary binary with a leading 0. All ones represent −1.
Write a negative value
To negate a representable value, invert every bit and add 1, keeping the width fixed. To encode −45 in 8 bits:
- Write +45 as 00101101.
- Invert all eight bits: 11010010.
- Add 1: 11010011, or 0xD3.
Stopping after inversion produces −46. Applying the full process to 11010011 gives 00101101 again, recovering +45.
Another route encodes as the unsigned value . Here , whose binary form is 11010011. The byte therefore means 211 unsigned or −45 signed. The bits have not changed; the type has.
Inversion followed by addition also has an arithmetic explanation. For an n-bit positive value x, inversion changes it to the unsigned value . Adding one gives , whose signed interpretation is −x. This connects the bit-by-bit method to the subtraction method and explains why leaving out the final 1 gives the wrong negative value.
Preserve a signed value in more bits
Sign extension copies the top bit into the new places on the left. Four-bit −3 is 1101; in 8 bits it is 11111101. Its negative top weight and added positive weights still total −3. Padding it with zeros would give 00001101, or +13. Positive values extend with zeros: 0011 becomes 00000011.
Recognize the endpoints
Two's complement supports ordinary binary addition for results that fit. In 4 bits, 0101 plus 1101, meaning 5 plus −3, gives 1 0010. Keeping the low four bits gives 0010, or 2. This lets the same basic addition hardware handle signed and unsigned values.
An out-of-range result is different: 8-bit 127 plus 1 leaves 10000000, which reads as −128. Also, −128 has no positive counterpart in 8 bits. Inverting 10000000 and adding 1 returns 10000000 because +128 is outside the range. Widen the representation before forming that positive value.
Key Takeaways
- The top bit has weight −2ⁿ⁻¹ in n-bit two's complement.
- Two's complement has one zero and one more negative value than positive values.
- Negate by inverting every bit and adding 1 within the fixed width.
- Sign extension copies the top bit into added positions.
- The most negative value has no positive counterpart in the same width.
- The same pattern can have different signed and unsigned meanings.
3Store fractions and floating-point values
Whole-number places extend to the right of the binary point as halves, quarters, and smaller fractions. Some decimal fractions end in binary, while others require an endless pattern. Fixed point reserves a set number of fraction places; floating point stores a scale as well as a significand. Reading these formats makes both their wide range and their rounding errors understandable, including the familiar result of adding 0.1 and 0.2.
3.1 Binary fractions and fixed point
The first place after the binary point is one half. Each later place is half the one before: one quarter, one eighth, one sixteenth, and so on. A 1 contributes that fraction; a 0 leaves it out. The whole-number places to the left keep their usual powers of two.
Read and build a binary fraction
For , the whole part is 4 plus 1. The fraction part is one half plus one eighth, giving .
To convert a decimal fraction, multiply it by 2 repeatedly. The whole part of each result is the next binary digit; keep only the fractional part for the next multiplication. For 0.375:
- , so the first bit is 0.
- , so the next bit is 1; keep 0.5.
- , so the next bit is 1 and the process stops.
The result is . Its value is one quarter plus one eighth, or 0.375. These bits are read in the order found, unlike the remainders in whole-number division.
Decide whether the expansion ends
Reduce the fraction to lowest terms. It has a finite binary expansion exactly when its denominator is a power of 2. Values such as 0.5, 0.25, 0.75, and 0.375 meet that test. For example, 0.375 is 3/8, and eight is a power of two.
Decimal 0.1 is 1/10. Its denominator includes a factor of 5, so its binary expansion repeats: . Just as one third cannot end in decimal, one tenth cannot end in binary. The short written form "0.1" therefore needs an approximation when only a limited number of binary places are available. The same issue affects 0.2 and 0.3.
The denominator rule follows from the places themselves. A finite string ending at the fth fraction place can be written as an integer divided by . Reducing that fraction can remove factors of two, but it cannot introduce another prime factor into the denominator. A reduced denominator containing five therefore cannot equal any such finite binary sum.
Reserve a fixed scale
A fixed-point representation gives a set number of bits to the fractional part. With four whole-number bits and four fraction bits, 0110.1000 means 6.5. The smallest step is , and the largest unsigned value is 1111.1111, or 15.9375.
Equivalently, the stored eight-bit integer is scaled by 1/16. The pattern 01101000 has unsigned value 104; dividing by 16 gives 6.5. The point is part of the interpretation, so it need not be stored as an extra symbol.
Keeping eight total bits but using five whole-number bits and three fraction bits makes the step 0.125 and the maximum 31.875. You gain range but lose fine spacing. Fixed point represents multiples of its step exactly within its range.
An exact count of cents uses a related scaling idea: 19.99 monetary units becomes the integer 1999 cents. For measurements covering very different sizes, floating point stores a movable scale, letting the same width cover a much wider range than fixed point.
Key Takeaways
- Binary fraction places are 1/2, 1/4, 1/8, and so on.
- Multiply a fractional part by 2 and read the whole parts in order.
- A reduced fraction terminates in binary exactly when its denominator is a power of 2.
- Fixed point trades range against fractional resolution at a fixed total width.
3.2 Read and write IEEE 754 fields
Floating point writes a value in binary scientific notation. For example, 6.25 is . The leading part is the significand, and the exponent sets its scale. IEEE 754 defines widely used formats for storing these parts.
Know the fields
| Format | Total | Sign | Exponent | Fraction | Bias |
|---|---|---|---|---|---|
| Single, binary32 | 32 bits | 1 | 8 | 23 | 127 |
| Double, binary64 | 64 bits | 1 | 11 | 52 | 1023 |
For a normal value, the reading is . Here is the sign bit, is the unsigned stored exponent, and is the fraction field. A sign bit of 0 means positive; 1 means negative. Changing only the sign bit negates a floating-point value.
The stored exponent equals the true exponent plus the bias. In single precision, exponent 2 becomes 129, or 10000001; exponent −3 becomes 124, or 01111100. Normal stored exponents run from 1 to 254, representing −126 through 127.
A normal binary significand always begins with 1, so the format omits that hidden bit. Only the bits after the point enter the fraction field. This gives 24 significant binary digits in single precision and 53 in double.
Encode −6.25 step by step
First normalize its magnitude: . Then fill the fields:
- Negative value: sign 1.
- Exponent 2: add 127 to get 129, written 10000001.
- Fraction .1001: store 1001 followed by 19 zeros.
The result is 1 10000001 10010000000000000000000, or 0xC0C80000. Fraction padding goes on the right because these places continue after the point. Storing the leading 1 would shift the fraction's meaning.
A negative true exponent moves the scale below one. For 0.15625, the binary form is . Its binary32 sign is 0 and its stored exponent is 124, or 01111100. The fraction starts 01 and is padded on the right. The hidden 1 still belongs to the normalized significand even though the complete number is smaller than one.
Decode a pattern
The single-precision pattern 0x41200000 splits into 0 10000010 01000000000000000000000. The sign is positive. The exponent field is 130, so subtract 127 to obtain 3. Restore the hidden 1 to get . Finally, .
Check reserved exponents first
The normal formula does not describe every pattern:
| Exponent field | Fraction field | Meaning |
|---|---|---|
| All zeros | Zero | +0 or −0, selected by sign |
| All zeros | Nonzero | A subnormal value, with leading 0 |
| All ones | Zero | Positive or negative infinity |
| All ones | Nonzero | NaN, "not a number" |
Subnormals represent very small values without the hidden 1. NaN can result from an invalid numerical operation such as 0 divided by 0. IEEE 754-2019 defines these formats.
Key Takeaways
- Single precision has fields of 1, 8, and 23 bits; double has 1, 11, and 52.
- Subtract the exponent bias when decoding; add it when encoding.
- Normal values have an unstored leading 1.
- Right-pad the fraction field with zeros.
- Exponent fields of all zeros or all ones have special meanings.
- Floating-point sign and exponent fields are not a two’s complement integer.
3.3 Range, precision, and rounding error
A floating-point format can cover a vast range without representing every value in that range. The exponent controls scale; the fraction field controls how many significant bits distinguish nearby values. Range and precision answer different questions.
Compare single and double precision
Single precision reaches about and has about seven significant decimal digits. Its smallest positive normal value is about . Double reaches about , has about 15–16 significant decimal digits, and has a smallest positive normal value of about . Subnormal values extend below the normal minimum in each format.
Significant digits are counted from the first meaningful digit, not from the decimal point. A large exponent does not create more fraction bits. In single precision the gap above 1 is . Between and the gap is 2, so the integer 16,777,217 is unavailable even though it lies far below the maximum finite value.
Round to a value that fits
IEEE 754's default is round to nearest, ties to even. Choose the nearer representable value; at an exact halfway point, choose the one whose last retained significand bit is even. Thus 16,777,217 rounds to 16,777,216 in single precision.
The gap between the intended value and the stored value is rounding error. In single precision, 0.1 is stored as 0.100000001490116119384765625. In double it is approximately 0.10000000000000000555. More precision reduces this error but cannot make a repeating expansion terminate.
Understand a familiar result
With ordinary IEEE 754 double arithmetic, adding 0.1 and 0.2 produces a stored result commonly displayed as 0.30000000000000004. It differs from the stored approximation of 0.3, so 0.1 + 0.2 == 0.3 is false in languages such as Python and JavaScript. For measured results, compare the difference with a tolerance chosen for the scale and purpose of the task.
Many values are exact. Double precision holds every integer from through exactly. Values such as 0.5 and 0.375 also have short binary forms that fit both its significand and exponent range.
Choose a suitable number type
Counts and identifiers suit integers. Exact financial amounts suit whole minor units, such as cents, or a decimal number type. Measurements and scientific calculations often suit floating point. A magnitude too large for the format can overflow to infinity; under the default rounding rule, single-precision becomes positive infinity. Very small results may become subnormal or round to zero.
Display conventions are separate from storage. The spellings "3.14" and "3,14" can name the same number in different locales. A text reader must know that convention; it might otherwise reject the comma or read the value as 314. Changing the printed separator does not improve binary precision.
Key Takeaways
- Range controls magnitude; precision controls the spacing of nearby values.
- Floating-point gaps grow as magnitude grows.
- The default rounding rule is nearest, with exact ties going to an even last bit.
- A short decimal fraction can still need rounding in binary.
- Choose integer, decimal, or floating-point storage to match the task.
4Turn characters into codes and bytes
Text needs an agreement between the software that writes it and the software that reads it. ASCII gives a small set of characters numeric codes. Unicode provides a shared code space for many writing systems, while encodings such as UTF-8 determine the actual bytes. Distinguishing a displayed character from a code point and from a byte helps you calculate text sizes and explain why a correctly saved file can appear garbled.
4.1 ASCII codes and their limits
To store text, a system assigns characters numeric codes and writes those numbers as bits. A character code only works when the reader uses the same agreement as the writer. The byte for a letter is a coded label; it is not a tiny picture of that letter.
Read the ASCII table
ASCII, the American Standard Code for Information Interchange, was first published in 1963. It uses 7 bits for 128 codes, numbered 0–127. In byte-based storage, an ASCII code usually fills one byte with a leading 0.
| Codes | Meaning |
|---|---|
| 0–31 and 127 | Control characters |
| 32 | Space |
| 48–57 | Digits "0"–"9" |
| 65–90 | Uppercase "A"–"Z" |
| 97–122 | Lowercase "a"–"z" |
Punctuation occupies the gaps. Codes 32–126 form 95 printable characters, including space. Controls affect text handling without printing a visible symbol: tab is 9, line feed is 10, and carriage return is 13.
Encode a short string
The text "Hi!" has three characters. Their decimal codes are 72, 105, and 33; in hex they are 0x48, 0x69, and 0x21. As full bytes, the text becomes 01001000 01101001 00100001. The exclamation mark needs a code just as the letters do.
A lowercase ASCII letter's code is 32 above its uppercase version. "A" is 65, or 01000001, while "a" is 97, or 01100001. That single changed bit accounts for the difference. The ordering also puts all uppercase letters before all lowercase letters. A simple code-based sort therefore places "Zebra" before "apple"; it does not follow ordinary dictionary ordering.
Separate a digit from a number
The character "7" has decimal code 55 and byte 00110111. The integer 7 has byte 00000111. To recover a digit's numeric value from its ASCII code, subtract 48, the code for "0": . This works because the ten digit codes are consecutive.
Storage depends on which representation is chosen. The text "2026" needs four ASCII bytes, one per digit. The integer 2026 fits in two bytes as a 16-bit unsigned value. Text preserves the sequence of characters; an integer represents the numerical value. For example, a text identifier can preserve leading zeros that an integer does not distinguish.
To encode a longer string, process every character in order, including spaces, punctuation, and controls. Decoding reverses the lookup one code at a time under the same table. The sequence matters: swapping two valid codes can still produce valid ASCII, but it produces different text. A successful lookup establishes that codes are recognized, not that they have the intended order or meaning.
See why code pages caused trouble
ASCII has no accented letters such as "é", "ñ", or "ü", and no Greek, Cyrillic, Arabic, or Chinese characters. Later 8-bit code pages used values 128–255 for extra symbols, but they did not agree on the additions.
For example, byte 0xE9 means "é" in Latin-1 but "й" in Windows-1251. Windows-1252 is another common code page. A byte value therefore cannot identify a non-ASCII character without knowing the encoding. Using the wrong table can produce readable-looking symbols that are still the wrong text.
Key Takeaways
- ASCII defines 128 codes using 7 bits, usually stored one per byte.
- Printable characters include spaces and punctuation; controls have other roles.
- Digit characters have different codes from the integers they name.
- Different legacy code pages can assign different characters to the same byte.
4.2 Unicode code points and UTF encodings
Unicode assigns characters from writing systems around the world a shared set of numbers called code points. "A" is U+0041, "é" is U+00E9, "Ж" is U+0416, "中" is U+4E2D, and "😀" is U+1F600. The U+ notation uses hexadecimal with at least four digits.
Separate a code point from its bytes
The code space runs from U+0000 to U+10FFFF, or 1,114,112 positions, with more than 150,000 assigned characters. A code point identifies a character or a reserved position; an encoding determines its byte representation.
| Encoding | Storage for a valid character code point |
|---|---|
| UTF-8 | 1–4 bytes |
| UTF-16 | 2 bytes through U+FFFF; 4 bytes above it |
| UTF-32 | 4 bytes |
The surrogate range U+D800–U+DFFF is reserved for UTF-16's pairing mechanism; isolated surrogates are not valid characters to encode in these forms. A pair of UTF-16 code units represents one supplementary code point. For example, "😀" is D83D DE00 in UTF-16.
Read UTF-8's byte ranges
UTF-8 preserves ASCII: U+0000–U+007F use one byte. U+0080–U+07FF use two; valid character code points in U+0800–U+FFFF use three; U+10000–U+10FFFF use four. This makes English ASCII text byte-for-byte compatible with UTF-8.
A single-byte character starts with 0. Longer characters start with 110, 1110, or 11110 for two, three, or four bytes. Every continuation byte starts with 10. The remaining bits carry the code point.
For "é", U+00E9, the 11-bit value is 00011101001. Split it into five bits and six bits: 00011 and 101001. Insert them into 110xxxxx 10xxxxxx to get 11000011 10101001, or C3 A9. The code point 00E9 is not itself the UTF-8 byte sequence.
Encoding and decoding must also respect the byte prefixes. A UTF-8 continuation byte is not a standalone ASCII byte: its first two bits are 10, so it belongs inside a longer character sequence. Removing part of a multibyte character at a byte limit can leave an incomplete sequence. Storage length and the boundaries at which text can be split are therefore connected.
Count the right objects
"café" has four displayed characters but five UTF-8 bytes: 63 61 66 C3 A9. "€" uses E2 82 AC, three bytes; "中" uses E4 B8 AD, also three; "😀" uses F0 9F 98 80, four. A byte limit can therefore allow fewer characters than its numeric size suggests.
One displayed character can also contain multiple code points. "é" can be U+00E9 or "e" followed by U+0301, a combining acute accent. The second form uses three UTF-8 bytes, 65 CC 81. Normalization converts equivalent sequences to a common form for comparison. The displayed emoji "👍🏽" contains two code points, U+1F44D and U+1F3FD, totaling eight UTF-8 bytes.
Diagnose garbled text
UTF-8 "café" read as Windows-1252 becomes "café": C3 and A9 are treated as separate characters. This is mojibake, caused by decoding with the wrong encoding. Correct decoding can recover the text while the original bytes remain intact. A web page can declare its encoding with <meta charset="utf-8">.
Key Takeaways
- A code point identifies a character; an encoding chooses its bytes.
- UTF-8 uses one to four bytes, preserving ASCII unchanged.
- Continuation bytes in UTF-8 begin with 10.
- A displayed character, a code point, and a byte are different counting units.
- Normalization can align equivalent character sequences.
- Decoding with the wrong encoding can produce mojibake.
5Measure pictures and sound in bits
Pictures and recordings turn visual and sound detail into numbers. A bitmap stores a grid of pixel values; sampled audio stores measurements taken at regular times. Their storage depends on how many values are kept and how many bits each value needs. These choices also affect what detail survives. Vector drawings and MIDI take a different approach by describing shapes or notes as instructions that a device later turns into an image or sound.
5.1 Pixels, RGB, palettes, and transparency
A bitmap, also called a raster image, is a grid of pixels. Each pixel holds a color value. The width and height give the image's resolution: 1920 by 1080 means pixels. A pixel count describes the grid, not its printed size in meters.
Assign enough bits to each pixel
The color depth is the number of bits used for a pixel's color. A depth of bits allows possible codes. One bit can distinguish two colors. Eight-bit grayscale can distinguish 256 intensities, usually from 0 for black to 255 for white.
A simple 3 by 3 image can use 1 for black and 0 for white. A black plus sign is represented by rows 010, 111, and 010. Nine pixels at one bit each need nine bits of pixel information. Actual file storage may include padding and other information beyond those bits.
Mix light with RGB
RGB stores red, green, and blue light intensities. With 8 bits per channel, each intensity ranges from 0 to 255, and a pixel uses 24 bits. The number of possible colors is .
| RGB values | Color |
|---|---|
| (0, 0, 0) | Black |
| (255, 255, 255) | White |
| (255, 0, 0) | Red |
| (0, 0, 255) | Blue |
| (255, 255, 0) | Yellow |
RGB is additive mixing of light. Combining red and green light gives yellow. A prediction based on mixing paint uses a different process and gives the wrong model for a screen.
Read hex color codes
A web color uses #RRGGBB: two hex digits for red, then green, then blue. #FF8000 means (255, 128, 0), an orange. #808080 means (128, 128, 128), a mid gray; equal channel values produce a gray. #0000FF gives the largest blue value with red and green at zero.
Each pair is one byte. Thus FF is 255, not a pair of separate color intensities. The # marks the whole RGB code and does not occupy a channel.
The RGB and palette models answer the pixel lookup differently. For direct RGB, reading the pixel gives its three channel intensities immediately. For indexed color, reading the pixel gives an entry number, and a second lookup supplies the intensities. Changing a palette entry can therefore change many displayed pixels that share the same index, even while their stored pixel indexes remain unchanged.
Store a palette index
When an image uses few colors, it can keep a palette, a table of the selected colors. A pixel then stores an index into that table. A 16-color palette needs four bits per pixel because four bits distinguish 16 entries. The palette itself also takes storage. GIF uses up to 256 palette colors, allowing an 8-bit index per pixel.
Add transparency
An alpha channel describes opacity. A common 8-bit scale uses 0 for fully transparent and 255 for fully opaque, with intermediate values for partial transparency. Adding that channel to 24-bit RGB gives 32-bit RGBA. Alpha is separate from red, green, and blue: a fully transparent pixel can still have stored color values that do not show in the final image.
Key Takeaways
- A bitmap stores a grid of pixel values.
- Color depth sets the number of color codes available per pixel.
- Ordinary RGB uses three 8-bit channels, totaling 24 bits.
- A palette index selects a color from a table.
- An alpha channel adds opacity information; 8-bit alpha makes RGB into 32-bit RGBA.
5.2 Calculate image and video storage
An uncompressed bitmap's pixel data grows with its pixel count and its bits per pixel. Keeping the units attached to each step helps separate the amount of information from the byte size reported by a file viewer.
Calculate pixel data
Use . Divide by 8 for bytes. Width and height must be multiplied because every row contains a full width of pixels.
For 1920 by 1080 at 24 bits per pixel, first find 2,073,600 pixels. Multiply by 24 to get 49,766,400 bits, then divide by 8 to obtain 6,220,800 bytes. That is about 6.2 MB, or 5.93 MiB. Changing the unit does not change the underlying pixel data.
For 640 by 480 at 8-bit grayscale, there are 307,200 pixels. Eight bits each give 2,457,600 bits; dividing by 8 gives 307,200 bytes, about 307 kB. Here one byte per pixel makes the final byte count equal to the pixel count.
Predict changes before calculating
Doubling the width doubles the pixels in each row. Doubling the height doubles the rows. Doubling both therefore multiplies the pixel count and storage by four. Raising depth from 8 to 24 bits per pixel triples storage at the same resolution. These factors multiply if both change.
The raw calculation gives pixel data, not necessarily a complete image file. A file also stores metadata, such as width, height, color depth, and format. A photo may record camera settings, date, and location. Palette tables, headers, padding, and compression can also change the final byte size.
For depths below eight bits, calculate the whole payload in bits before converting. A 100 by 60 one-bit image contains 6,000 pixel bits, or 750 packed bytes. Treating each pixel as a byte would overstate that payload eightfold. If a format pads each row to a particular boundary, its padding must be added separately; it is not a change in the color depth.
Extend the calculation to video
A video presents a sequence of images called frames. At 30 frames per second, 1920 by 1080 RGB video needs bytes of uncompressed picture data each second, about 187 MB/s. Multiplying by duration gives the total picture data. Sound adds its own storage.
This large rate explains why ordinary video files are compressed. The rate of a compressed video is a separate quantity; it cannot be inferred from resolution alone.
Compare raster and vector images
| Bitmap | Vector |
|---|---|
| Stores a grid of color values | Stores shapes and drawing instructions |
| Suits photographs and texture | Suits logos, diagrams, and font outlines |
| Enlarging the grid reveals pixels | Shapes can be redrawn at a larger scale |
A vector file can describe a line from (0, 0) to (100, 50), or a circle by its center, radius, and fill. It need not store a separate color value for every point inside the circle. Simple drawings can therefore be small. SVG is a common vector format.
A display still needs pixels. Rasterization turns the shapes into a pixel grid at the requested size. Scaling vector instructions preserves the shape's geometry; enlarging an existing bitmap cannot recover image detail that its original grid never recorded.
Key Takeaways
- Uncompressed bitmap bits equal width × height × bits per pixel.
- Divide bits by 8 before reporting bytes.
- Doubling both dimensions quadruples pixel data at the same depth.
- Raw video picture data equals bytes per frame × frame rate × duration.
- Metadata and compression make file size differ from a raw pixel calculation.
- Vector graphics store shapes that are rasterized for display.
5.3 Sample sound and calculate audio size
Sound is a vibration of air pressure. A microphone turns it into an analog electrical signal that varies continuously. An analog-to-digital converter takes regular measurements, called samples, and stores each one as a number.
Separate timing from measurement detail
The sample rate, measured in hertz, is the number of samples taken each second per channel. A rate of 44,100 Hz is 44.1 kHz. CDs use 44.1 kHz, video soundtracks commonly use 48 kHz, and traditional telephone audio uses 8 kHz. Samples record values at those instants; they are not a continuous record of every instant between them.
The bit depth sets how many levels each sample can use. Eight bits give 256 levels, 16 give 65,536, and 24 give 16,777,216. Rounding a measurement to a level is quantization. The difference from the original measurement produces quantization error, which can be heard as noise. More bits provide finer levels and reduce that error.
Sample rate controls detail in time; bit depth controls detail in measured amplitude. Increasing one does not replace increasing the other.
Capture the frequency range
The sampling theorem requires a sample rate greater than twice the highest frequency being captured. To capture 20 kHz, the rate must exceed 40 kHz. Exactly twice is insufficient for an arbitrary signal at the boundary.
At 44.1 kHz, the theoretical limit is below 22.05 kHz. The gap above about 20 kHz, the approximate upper limit of human hearing, gives room for an anti-aliasing filter. Frequencies above half the sample rate can appear as false lower frequencies, called aliasing. A converter filters those high frequencies before sampling.
A rate of 44,100 Hz applies to each channel, not to the recording as a combined stream. Stereo therefore stores 88,200 sample values each second. The channel factor belongs in the storage formula because each instant has a left value and a right value. It does not double the highest frequency each channel can capture; that limit still follows from its own sampling rate.
Calculate uncompressed audio
Mono has one channel; stereo has two. The payload size is
For a three-minute stereo recording at 44,100 Hz and 16 bits, the rate is bit/s. Multiply by 180 seconds to obtain 254,016,000 bits, then divide by 8: 31,752,000 bytes, about 31.8 MB.
A ten-second mono recording at 8,000 Hz and 8 bits gives bits, or 80,000 bytes. A stereo recording at the same settings would use twice as much.
Choose what to store
Higher rates and depths require more space. CD settings are generally enough for listening; studios often use 24 bits and 48 kHz or higher to leave room for processing and editing.
MIDI records note instructions: which notes, when they begin, their strength, and instrument choices. It can be much smaller than a sampled performance, but playback depends on the instrument sounds available. MIDI can describe a singer's melody as notes; it cannot contain the actual recorded voice.
Key Takeaways
- Sample rate counts measurements per second; bit depth counts bits per measurement.
- Quantization rounds a sample to one of the available levels.
- The sample rate must exceed twice the highest frequency being captured.
- Anti-aliasing filters remove high frequencies before sampling.
- Audio bits equal sample rate × bit depth × channels × seconds.
- MIDI stores performance instructions, not a recorded waveform.
6Compress data and choose a format
Compression reduces the bits needed to store or send data. Some methods replace repeated information with shorter descriptions that can be reversed exactly. Others remove detail from pictures and sound to achieve smaller files. You will follow simple codes, account for the information a decoder needs, and choose a format by what must survive. A file intended for editing or exact recovery has different needs from a final stream for listening or viewing.
6.1 Lossless codes and their limits
Lossless compression lets decompression rebuild the original bits exactly. Text, program files, spreadsheets, and other exact data need that property. ZIP, PNG, GIF, and FLAC are familiar lossless formats. They exploit redundancy: repeated or predictable information that has a shorter description.
Describe repeated runs
Run-length encoding, or RLE, replaces consecutive identical symbols with a count and the symbol. The 18-character string "AAAAAABBBCCCCCCCCD" becomes "6A3B8C1D", eight characters under this count-and-symbol convention. Decoding expands each pair: six As, three Bs, eight Cs, and one D.
The same idea suits flat-color image regions. The pixel row 0000000011110000 can be described as eight zeros, four ones, and four zeros. A real file must define how counts and symbols are stored so that decoding is unambiguous.
Short runs can make RLE larger. "ABCD" becomes "1A1B1C1D", doubling the character count before any header. Compression works only when the savings exceed the cost of describing the pattern.
Refer to a repeated sequence
A dictionary method replaces a repeated sequence with a reference. LZ-family methods underlie formats such as ZIP and PNG. In "to be or not to be", the second "to be" can be replaced by an instruction to go back 13 characters and copy five. Spaces count as characters. The decoder already has that earlier text and can reproduce the sequence from the reference.
Give common symbols shorter codes
A variable-length code uses different bit lengths for different symbols. Huffman coding builds codes from symbol frequencies. For "ABRACADABRA", A appears five times, B and R twice each, and C and D once each. A fixed-width code for five symbols needs three bits per symbol, or 33 bits for eleven letters.
One suitable prefix-free code is A = 0, B = 10, R = 110, C = 1110, and D = 1111. The encoded data uses bits. The code table adds overhead, so 23 bits alone is not the complete file size.
Prefix-free means no symbol's code begins another symbol's code. Reading 0110 therefore gives A followed by R without needing separators. This property lets a Huffman decoder recognize a symbol as soon as its code ends.
The decoder must know the coding convention as well as the payload. For a Huffman-style stream, it needs the symbol-to-code mapping; for RLE, it needs to distinguish a count from a symbol. A small message may save payload bits yet grow overall when this description is included. Compare complete original and encoded sizes when deciding whether a method actually reduced the file.
Measure savings and recognize limits
The compression ratio is original size divided by compressed size. Reducing 6 MB to 2 MB gives 3:1. Use the same unit on both sides.
No lossless method can shorten every possible file. There are different n-bit inputs but only bit strings shorter than n bits. Exact recovery requires different inputs to remain distinguishable, so they cannot all receive shorter outputs. Random data and already compressed files often shrink little or grow because of added overhead.
Key Takeaways
- Lossless decompression reproduces the original bits exactly.
- RLE describes identical consecutive symbols with counts.
- Dictionary methods replace repeated sequences with references.
- Huffman coding assigns shorter codes using symbol frequencies.
- A prefix-free code identifies symbol boundaries without separators.
- Compression ratio compares original size with compressed size.
- No lossless method shortens every possible input.
6.2 Lossy formats and quality choices
Lossy compression removes information to reduce file size. Decompression creates a close version of the original, with some detail permanently missing. Photographs, music, speech, and video can tolerate selected losses that exact text or program data cannot.
Compress pictures by visual importance
JPEG relies on human vision's different sensitivity to brightness, color, and fine detail. A typical JPEG reduces fine color resolution and rounds fine image detail represented in 8 by 8 blocks. Its quality setting controls how strongly information is discarded. Stronger compression can produce blockiness or blur and ringing near sharp edges.
A photograph can often reach about 10:1 with little visible loss. At that ratio, an image with 6,220,800 bytes of raw pixel data would use about 622,080 compressed bytes, roughly 0.6 MB. The ratio is an example, not a fixed property of every JPEG.
Compress sound by what can be heard
MP3 and AAC use perceptual coding. A quiet sound can be masked by a louder sound at a nearby frequency, so the encoder can devote fewer bits to information a listener is unlikely to hear. A smaller file can still sound very close to the original.
For a constant bit rate, size in bits equals bit rate times duration. At 128 kbit/s, a three-minute recording needs bits, or 2,880,000 bytes, about 2.9 MB. That is about one eleventh of the 1,411.2 kbit/s of uncompressed CD audio. The compressed rate already describes the encoded stream; do not multiply it by the original sample depth again.
Exploit similarities across video frames
Neighboring frames often show nearly the same scene. Video formats such as H.264 and AV1 compress image detail and describe many frames through changes or predictions from other frames. This removes repeated information across time as well as within each picture.
Match the format to the use
| Use | Suitable choice | Reason |
|---|---|---|
| Exact text, code, or data | Lossless archive | Every bit must survive |
| Photo for sharing | JPEG or another lossy image format | Small size with acceptable visual loss |
| Screenshot or logo | PNG | Preserves sharp edges and flat colors |
| Music for streaming | AAC, MP3, or Opus | Saves transfer capacity |
| Audio master for archiving | FLAC | Exact recovery of the audio samples |
Keep a lossless original for future editing. Repeated lossy decoding and re-encoding can add generation loss. Converting an already lossy JPEG to PNG preserves its current decoded pixels but cannot restore detail removed earlier.
Greater compression can cost quality, processing time, or both. The useful choice depends on what a file contains and how it will be used; the smallest file is not always the most useful one.
Key Takeaways
- Lossy compression permanently removes selected information.
- JPEG exploits visual sensitivity; lossy audio uses perceptual coding.
- Compressed-stream size follows bit rate × duration.
- Keep a lossless original when future editing or exact recovery matters.
- Changing a lossy file to a lossless format cannot recover discarded information.
Binary and Data Representation examples
1Build a code, then read its bits
12 steps
- 1IntroductionOne pattern, several readings
A stored pattern has two separate features: how many bits it occupies and how a reader interprets them. The eight bits 01000001 could mean a number, a text character, or a color intensity.
We will first choose enough bits to distinguish a collection of values, then read a numerical pattern using binary place values and hexadecimal. Changing the notation changes what you write, while keeping the value intact.
- 2ExplanationCount choices by doubling
Each bit has two choices, so each added bit doubles the number of patterns. Two bits give 00, 01, 10, and 11; three bits give eight patterns. In general, n bits give patterns.
To identify 26 letters, four bits fail because they give only 16 patterns. Five bits give 32 and leave six patterns unused. A code does not have to use every available pattern.
- 3ChallengeChoose a field for categories
A device must distinguish 90 categories. What is the smallest bit count that can encode them? How many patterns will remain unused?
---reveal---
Six bits give 64 patterns, too few. Seven give 128, so the field needs seven bits and leaves 38 patterns unused. The largest numeric label could be 89 if labels start at zero; that endpoint is different from the 90-category count.
- 4ConnectionRead the case of the unit letter
A byte has eight bits. That makes the case of the unit letter matter: b means bit and B means byte. A 40 Mbit/s link has an ideal payload ceiling of 5 MB/s before overhead.
Unit prefixes matter separately. One MB means one million bytes, while one MiB means 1,048,576 bytes. Converting a stored amount from MB to MiB changes the numerical reading without removing any data.
- 5ExplanationLine up binary places
The rightmost whole-number place is 1. Moving left gives 2, 4, 8, 16, 32, 64, and so on. A 1 selects a place and a 0 leaves it out.
For 101101, the selected places are 32, 8, 4, and 1, totaling 45. Leading zeros can fill a width without changing these places. A missing zero inside the pattern would shift some of the digits and change the value.
- 6ExampleSelect the powers for 156
The largest power of two not exceeding 156 is 128. Subtract it to leave 28. The 64 and 32 places do not fit, so give them zeros.
Take 16 from 28, leaving 12. Take 8, leaving 4, then take 4 to reach zero. The final two places, 2 and 1, receive zeros. Across the places 128 through 1, the bits are 10011100. Keeping every unused place prevents the chosen powers from shifting.
- 7TipReverse whole-number remainders
Repeated division is another route to the same pattern. Dividing a whole number by two gives its last bit as the remainder. Dividing the quotient finds the next bit to the left.
For 156, the remainders arrive as 0, 0, 1, 1, 1, 0, 0, 1. Read from last to first to obtain 10011100. The reverse order is necessary because division discovers the least significant place first.
- 8ChallengeConvert and check a new value
Write decimal 109 in eight binary places, then use your result to explain whether 109 is odd.
---reveal---
The chosen powers are 64, 32, 8, 4, and 1, so the pattern is 01101101. Their sum is 109, which checks the conversion. The last bit is 1; all the other places contribute even quantities, leaving an odd whole number. The leading zero fills the byte without changing the value.
- 9ExplanationReplace nibbles with hex digits
Hex has sixteen digits: 0–9 followed by A–F for ten through fifteen. Four bits also distinguish sixteen patterns, so each hex digit names one nibble.
Split 10011100 into 1001 and 1100. The first group is nine and the second is twelve, written C. The result is 0x9C. Hex is four times shorter than binary in digit count, while keeping a direct link to groups inside the byte.
- 10ExampleGroup a short pattern from the right
To convert 101101, form groups from the right: 10 and 1101. Pad the far-left group to 0010. The groups now give hex 2 and D, so the value is 0x2D.
Check using hex place values: two sixteens plus thirteen ones gives 45. Grouping from the left would put the final short group in the wrong place. Inside a full hex expansion, each digit must retain all four bits.
- 11ChallengeConnect bits, width, and hex
A fixed-width unsigned field stores 0xB4. How many bits are shown by its two hex digits, what is its binary pattern, and what decimal value does it hold?
---reveal---
Two hex digits represent eight bits. B expands to 1011 and 4 to 0100, so the byte is 10110100. Its selected places sum to 128 + 32 + 16 + 4 = 180. Equivalently, eleven sixteens plus four gives 180.
- 12RecapThree checks for a stored value
Check capacity, notation, and units separately. A field needs enough patterns for all its possible values. Binary selects powers of two; hex groups those bits into fours from the right.
The stored value survives a change of written base or storage unit. A changed data interpretation can give the same bits a different meaning, so the pattern and the rule for reading it belong together.
2Read signed values and preserve their width
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionA width needs an interpretation
- 2ExplanationReserve a pattern for zero
- 3ExampleFollow unsigned wraparound
- 4ChallengeChoose enough room for a count
- 5ExplanationGive the leading bit a negative weight
- 6ExampleStart the pattern for −45
- 7ExampleComplete the negation
- 8ChallengeEncode another negative integer
- 9Key InsightExtend the sign, not just the zeros
- 10ChallengeWiden before taking the opposite
- 11RecapKeep the rule with the pattern
3Build a floating-point encoding
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionA value and a scale
- 2ExplanationRead the fraction places
- 3ExampleGenerate a terminating fraction
- 4Key InsightPredict whether the digits end
- 5ChallengeFind the scale in fixed point
- 6ExplanationRecognize the fields
- 7ExampleWrite 6.25 in binary
- 8ExampleEncode the exponent
- 9ExampleStore only the fraction
- 10ExampleJoin the three fields
- 11ChallengeDecode a different normal value
- 12TipClassify reserved patterns first
- 13ExplanationSeparate range from spacing
- 14Key InsightWatch the gap grow
- 15ChallengeRound a halfway integer
- 16ChallengeChoose a type for an exact amount
- 17RecapRead the format before the value
4Follow text from characters to bytes
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionText needs an agreement
- 2ExplanationFind the ASCII character code
- 3ExampleEncode letters and punctuation
- 4ChallengeRecover a numeric digit
- 5ConnectionWhy a single byte was not enough
- 6ExplanationIdentify before encoding
- 7ExampleSplit the bits for é
- 8ExampleFinish the two encoded bytes
- 9ChallengeCount a mixed-script string
- 10Key InsightOne appearance can have two forms
- 11ChallengeDiagnose the garbled word
- 12RecapKeep three counts separate
5Budget storage for pictures and recordings
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionCount values, then bits per value
- 2ExplanationBuild an RGB pixel
- 3ConnectionAdd transparency or use a palette
- 4ChallengeRead a color and its depth
- 5ExampleStart with the pixel grid
- 6ExampleConvert the picture to bytes
- 7ChallengeScale the grid and add frames
- 8Key InsightA drawing can store instructions
- 9ExplanationSample timing and amplitude separately
- 10ExplanationFilter before sampling
- 11ExampleFind the audio rate first
- 12ChallengeCalculate a different recording
- 13ConnectionNotes can replace a waveform
- 14ChallengeCompare two storage changes
- 15RecapKeep the factors and units visible
6Compress without confusing size and fidelity
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTwo ways to get a smaller file
- 2ExplanationReplace runs with counts
- 3ChallengeTry long runs and short runs
- 4ConnectionPoint to a sequence already seen
- 5ExampleGive frequent symbols short codes
- 6ChallengeDecode the stream in order
- 7Key InsightSome inputs must stay large
- 8ExplanationRemove less noticeable media detail
- 9ExampleUse a compressed bit rate directly
- 10ChallengeProtect a master while sharing a copy
- 11ChallengeCompare a ratio with a transfer budget
- 12RecapMatch the guarantee to the purpose
Binary and Data Representation practice questions
Set 1: Apply formats and calculate payloads10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
Show answerHide answer
Set 2: Read patterns and estimate storage10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 3: Interpret the same bits in different ways10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Diagnose errors and connect representations10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 5: Combine limits, encodings, and size choices10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Aliasing
Alpha channel
Analog signal
ASCII
Audio bit depth
B
Base
Binary
Binary point
Bit
Bit rate
Bitmap
Byte
C
Character code
Code page
Code point
Color depth
Compression
Compression artifact
Compression ratio
Control character
D
Data type
Dictionary method
E
Encoding
Exponent bias
F
Finite binary expansion
Fixed point
Fixed width
Floating point
Frame
G
Generation loss
H
Hex digit
Hexadecimal
Hidden bit
Huffman coding
I
IEC binary prefix
IEEE 754
Image metadata
L
Least significant bit
Lossless compression
Lossy compression
M
MIDI
Mojibake
Most significant bit
N
NaN
Negation
Nibble
Normalization
O
Overflow
P
Palette
Perceptual coding
Pixel
Positional notation
Precision
Prefix-free code
Q
Quantization
R
Range
Rasterization
Redundancy
Resolution
RGB
Rounding error
Run-length encoding
S
Sample
Sample rate
Sampling theorem
SI storage prefix
Sign bit
Sign extension
Sign-magnitude
Significand
Subnormal value
T
Ties to even
Two's complement
U
Underflow
Unicode
Unsigned integer
UTF-8
UTF-16
V
Vector graphics
W
Wraparound
#
0x prefix
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.