15  Binary Number Systems

In 60 Seconds

Binary is the language computers use to represent all data, using only 0s and 1s. Every IoT sensor reading must be converted from a smooth analog signal to a digital binary number through an ADC (Analog-to-Digital Converter), and the number of bits determines precision – an 8-bit ADC gives 256 levels while a 12-bit ADC gives 4,096 levels. When working with decimal sensor values in code, never compare floating-point numbers with == because rounding errors make exact comparison unreliable.

Key Concepts
  • Binary Number System: A base-2 number system using only digits 0 and 1; each position represents a power of 2 (1, 2, 4, 8, 16…); binary 1011 = 1x8 + 0x4 + 1x2 + 1x1 = 11 in decimal
  • Hexadecimal: Base-16 number system using digits 0-9 and letters A-F; one hex digit represents exactly 4 bits (a nibble); commonly used to represent binary data compactly: 0xFF = 11111111 in binary = 255 in decimal
  • Bit and Byte: A bit is a single binary digit (0 or 1); a byte is 8 bits (256 possible values, 0-255); microcontroller registers, ADC outputs, and sensor data are all expressed in bits and bytes
  • Two’s Complement: The standard representation of signed integers in binary; the most significant bit (MSB) represents a negative power of 2; for an 8-bit signed integer: range is -128 to +127; used by accelerometers and ADCs to represent negative values
  • Bitwise Operations: AND (&), OR (|), XOR (^), NOT (~), shift left (<<), and shift right (>>) operate on individual bits; essential for extracting sensor data from multi-byte register values: value = (high_byte << 8) | low_byte
  • LSB and MSB: Least Significant Bit (LSB): the bit with the smallest value (position 0); Most Significant Bit (MSB): the bit with the largest value (position N-1); sensor data is often transmitted MSB-first or LSB-first — check the datasheet to combine bytes correctly
  • Fixed-Point Arithmetic: Representing fractional numbers by treating a fixed number of bits as the fractional part; used in embedded systems where floating-point hardware is absent; a Q8.8 format uses 8 bits for integer and 8 bits for fraction, giving 1/256 resolution
  • Bit Masking: Using bitwise AND with a mask to isolate specific bits from a register value; e.g., status & 0x04 isolates bit 2 (the third bit); used to check specific flag bits in sensor status registers

15.1 Learning Objectives

By the end of this section, you will be able to:

  • Convert Binary Numbers: Translate between decimal and binary number systems using place-value decomposition
  • Apply Powers of 2: Calculate ADC resolution ranges from bit depth
  • Interpret Place Values: Use positional notation in base-2 arithmetic
  • Analyse Floating Point: Explain IEEE 754 representation and identify its precision limitations
  • Implement Safe Comparisons: Write code that correctly compares floating-point sensor values using threshold-based techniques

Binary is the language of all computers and microcontrollers – instead of using 0 through 9 like we do, they only use 0 and 1. Every sensor reading, every image, every sound in a digital device is stored as a pattern of zeros and ones. Understanding binary helps you grasp why a “12-bit sensor” is more precise than an “8-bit sensor” and what that means for your measurements.

15.2 Prerequisites

Before diving into this chapter, you should be familiar with:

  • Basic Mathematics: Understanding of exponents and place value systems (decimal notation)
  • Electricity Fundamentals: Basic understanding of voltage as a measurable quantity

Analog and digital are like the difference between a slide (smooth) and stairs (steps)!

15.2.1 The Sensor Squad Adventure: The Translator

Sammy the Sensor had a problem. “Max, I can feel temperatures that go smoothly from cold to hot - like 20.1, 20.2, 20.3 degrees. But you only understand numbers like 20, 21, 22!”

Max the Microcontroller nodded. “You’re right, Sammy! I’m a digital thinker. I can only work with exact step numbers, like climbing stairs. But your feelings are analog - smooth like sliding down a slide.” This was a big problem! How could they work together?

Lila the LED had an idea. “What about our friend ADC Andy? He’s a translator!” ADC Andy arrived with a big smile. “I can help! When Sammy feels 20.7 degrees, I’ll translate it to the nearest step - 21 - so Max can understand!” Bella the Battery was curious. “But don’t you lose some information?” Andy explained, “A little bit, yes. But I can make my stairs have MORE steps - instead of big steps like 20, 21, 22, I can use tiny steps like 20.0, 20.1, 20.2. The more steps I use, the closer I get to Sammy’s smooth feelings!” Now Sammy could measure temperatures, Andy would translate them into step-numbers, and Max could process them. The Sensor Squad’s translation team was complete!

15.2.2 Key Words for Kids

Word What It Means
Analog Smooth signals that can be any value (like a slide)
Digital Step signals that jump between exact values (like stairs)
ADC A translator that changes smooth signals into step numbers
Resolution How many steps you have - more steps means more precise
Sampling Taking snapshots of a smooth signal to turn it into steps
Binary A number system using only 0 and 1 (how computers count)

15.2.3 Try This at Home!

The Temperature Translator Game!

  1. Get a cup of water and feel how warm it is
  2. Try to describe the temperature in two ways:
    • Analog way: “It feels kind of warm, a bit cooler than my hand, slightly warmer than the air…”
    • Digital way: “I’ll call it a 6 out of 10” (pick a number from 1-10)
  3. Now try with MORE steps (1-100):
    • Is “62 out of 100” more precise than “6 out of 10”?

What you learned: When you pick a number, you’re doing what an ADC does - translating a smooth feeling into a step-number! More steps (higher resolution) means a more accurate translation, but you can never perfectly capture the smooth original feeling - you’re always rounding to the nearest step!

15.3 Getting Started: Analog vs Digital

Analog vs Digital: What’s the Difference?

Analogy: Think of a ramp vs stairs.

  • Analog = A smooth ramp (infinite positions)
  • Digital = Stairs (fixed steps, you’re on step 1, 2, or 3—never 1.5)
Analog-to-digital conversion diagram showing analog signals as continuous ramps and digital signals as discrete steps, illustrating the fundamental difference between the two representations.
Figure 15.1: Analog vs Digital Signals: Continuous Ramp vs Discrete Steps
The Real-World Problem

Everything we want to measure is analog, but computers only understand digital!

Real World (Analog) Computer Needs (Digital)
Temperature: 23.7°C ADC raw value: 00010111 (23 after rounding)
Light level: 847 lux Number: 847
Sound wave: smooth curve Samples: [128, 130, 145, ...]

Solution: Use an ADC (Analog-to-Digital Converter) to translate!

ADC conversion diagram showing how an analog sensor's continuous voltage output is converted to a binary digital value for microcontroller processing.
Figure 15.2: ADC Conversion Process: Temperature Sensor to Digital Value

15.4 Binary: The Language of Computers

15.4.1 What is a Bit?

Bit = Binary Digit = Smallest unit of information = 0 or 1

One transistor = One bit

Real-world binary examples:

  • Light switch: ON/OFF
  • Door: OPEN/CLOSED
  • Answer: YES/NO
  • Coin: HEADS/TAILS

15.4.2 Powers of 2: Why Binary Uses These Numbers

Binary groupings are always powers of 2:

Bits Calculation Possible Values Range
1 21 2 0-1
2 22 4 0-3
4 24 16 0-15
8 28 256 0-255
10 210 1,024 0-1023
12 212 4,096 0-4095
16 216 65,536 0-65535
32 232 4,294,967,296 0-4.3 billion

Why This Matters for IoT:

  • 8-bit ADC: 256 different sensor values
  • 10-bit ADC: 1,024 values (typical Arduino)
  • 12-bit ADC: 4,096 values (typical ESP32)
  • 16-bit ADC: 65,536 values (high-precision sensors)

Each additional bit doubles the resolution: \(2^{n+1} = 2 \times 2^n\). An 11-bit ADC has \(2^{11} = 2048\) steps, exactly twice the 10-bit ADC’s 1024 steps. For a 0-5V range, the 10-bit step size is \(5/1024 = 4.88\) mV, while 12-bit is \(5/4096 = 1.22\) mV (4× finer). Adding 2 bits (\(10 \rightarrow 12\)) multiplies resolution by \(2^2 = 4×\). To measure a 50mV sensor signal with 1% precision (0.5mV), you need \(\lceil \log_2(50/0.5) \rceil = \lceil \log_2(100) \rceil = 7\) bits minimum (\(2^7 = 128\) steps).


15.5 Binary Number System

Table showing binary powers of 2 from 2^0=1 to 2^10=1024, illustrating how bit depth determines ADC resolution ranges used in microcontroller analog-to-digital conversion
Figure 15.3: Powers of 2 and binary place values

15.5.1 Place Value in Binary

Just like decimal uses powers of 10, binary uses powers of 2:

Decimal (base 10):

237 = (2 × 10²) + (3 × 10¹) + (7 × 10⁰)
    = (2 × 100) + (3 × 10) + (7 × 1)
    = 200 + 30 + 7

Binary (base 2):

101 = (1 × 2²) + (0 × 2¹) + (1 × 2⁰)
    = (1 × 4) + (0 × 2) + (1 × 1)
    = 4 + 0 + 1
    = 5 (in decimal)

15.5.2 Example: Convert Decimal 37 to Binary

Step 1: Find largest power of 2 ≤ 37

Position 25 24 23 22 21 20
Value 32 16 8 4 2 1
Bit 1 0 0 1 0 1

Step 2: Calculate: - 37 ÷ 32 = 1 remainder 5 → Bit 5 = 1 - 5 ÷ 16 = 0 → Bit 4 = 0 - 5 ÷ 8 = 0 → Bit 3 = 0 - 5 ÷ 4 = 1 remainder 1 → Bit 2 = 1 - 1 ÷ 2 = 0 → Bit 1 = 0 - 1 ÷ 1 = 1 → Bit 0 = 1

Decimal number 37 converted to 6-bit binary representation 100101, showing place values: 1×32 + 0×16 + 0×8 + 1×4 + 0×2 + 1×1 equals 37
Figure 15.4: Number 37 in binary representation

Step-by-step division process converting decimal 37 to binary 100101, showing successive division by powers of 2 with remainders Result: 37decimal = 100101binary

Verification: (1×32) + (0×16) + (0×8) + (1×4) + (0×2) + (1×1) = 32 + 4 + 1 = 37

Recommended: Intro to Binary Numbers (10 minutes)

Visual explanation of binary counting, conversion, and why computers use base-2.

15.5.3 Try It: Binary / Decimal Converter

Use the slider to pick a decimal number and see its binary representation, place values, and hexadecimal equivalent.


15.6 Floating Point Numbers

Problem: How to represent very large or very small numbers efficiently?

Solution: Floating point notation (scientific notation for computers)

15.6.1 Decimal Scientific Notation

Instead of:

  • 300,000,000,000 → Write: 3 × 1011
  • 0.000000000015 → Write: 1.5 × 10-11

15.6.2 Binary Floating Point (IEEE 754)

32-bit float representation:

Sign Exponent Significand (Mantissa)
1 bit 8 bits 23 bits

Example: 3.14159… stored as: - Sign: 0 (positive) - Exponent: biased by +127 (stored as 128 for 21) - Significand: fractional part after the leading 1 (implicit)

IoT Relevance:

  • Arduino (AVR): 32-bit floats only (float and double are both 32-bit)
  • ESP32: Hardware single-precision FPU; 64-bit doubles supported in software
  • Sensors: Temperature as 23.456°C stored efficiently
Floating Point Precision Limitations

Never compare floats with == in code!

Due to rounding errors, 0.1 + 0.2 may not exactly equal 0.3.

Correct:

if (abs(value1 - value2) < 0.0001) {
    // Close enough!
}

Recommended: Floating Point Numbers Explained (12 minutes)

How computers represent decimal numbers and why precision matters.


15.7 Quiz: Binary Fundamentals

What is the decimal value of binary 1101?

A) 11 B) 13 C) 15 D) 9

Show Answer

Answer: B) 13

\[1101_2 = (1×8) + (1×4) + (0×2) + (1×1) = 8 + 4 + 0 + 1 = 13_{10}\]

How many different values can a 16-bit ADC represent?

A) 16,384 B) 32,768 C) 65,536 D) 131,072

Show Answer

Answer: C) 65,536

\[Values = 2^{bits} = 2^{16} = 65,536\]

The actual digital output ranges from 0 to 65,535 (one less than total values).


Common Mistake: Confusing ADC Resolution with Measurement Range

The Mistake: Assuming that a “12-bit ADC” can measure 12 volts, or that increasing bit depth extends the measurable voltage range.

Why It Happens: The term “12-bit” sounds like it describes voltage capability, and datasheets often list resolution before reference voltage, creating confusion about what the bits actually control.

Real-World Example: A student tried to measure a 12V battery voltage with an ESP32’s 12-bit ADC. They expected accurate readings because “12-bit should handle 12 volts.” The ESP32 immediately damaged because its maximum input is 3.3V, not 12V. The 12-bit specification describes resolution (how many steps), not range (maximum voltage).

The Fix: Understand These Three Independent Specifications

Specification What It Controls ESP32 Example
Bit Depth (Resolution) Number of discrete steps 12-bit = 4,096 steps
Reference Voltage (Vref) Maximum measurable voltage 3.3V maximum input
Voltage Per Step Precision 3.3V / 4,096 = 0.806 mV/step

Key Insight: Resolution (bits) and range (Vref) are independent: - A 12-bit ADC with 5V reference: 5V / 4,096 = 1.22 mV/step - A 12-bit ADC with 3.3V reference: 3.3V / 4,096 = 0.806 mV/step - A 16-bit ADC with 3.3V reference: 3.3V / 65,536 = 0.0504 mV/step

Same bit depth, different ranges. Same range, different precision.

To measure 12V on ESP32’s 12-bit ADC:

  1. Add a voltage divider: R1=27kΩ, R2=10kΩ
    • Output voltage = 12V × (10k / (27k + 10k)) = 3.24V (safe for ESP32)
  2. Read ADC value (0-4095)
  3. Convert back: Actual voltage = ADC_value × (3.3V / 4095) × ((27k + 10k) / 10k)

Example Calculation:

  • ADC reads 4000
  • Step voltage = 4000 × (3.3V / 4095) = 3.22V (at ADC input)
  • Actual battery = 3.22V × 3.7 (divider ratio) = 11.91V

Rule of Thumb: Bit depth = precision (how finely you measure). Reference voltage = range (how high you measure). Always apply voltage dividers for inputs exceeding Vref.

Concept Relationships: Binary and Digital Representation
Concept Relates To Relationship
Binary Place Values ADC Resolution 2^n formula determines how many discrete voltage levels the ADC can distinguish
Floating-Point (IEEE 754) Sensor Data Processing Temperature readings like 23.456°C stored efficiently but comparisons need threshold
Powers of 2 Memory and Data Storage IoT buffers sized in powers of 2 (256-byte, 512-byte, 1024-byte) for efficiency

Cross-module connection: ADC Fundamentals - Applies binary powers of 2 to calculate ADC voltage steps and quantization error

15.8 Summary

This chapter covered the binary number system - the foundation for all digital electronics:

  • Analog vs. Digital: Real-world signals are continuous (analog); computers work with discrete values (digital)
  • Binary (Base-2): Uses only 0 and 1; each position represents a power of 2
  • Powers of 2: Determine ADC/DAC resolution (8-bit = 256 values, 12-bit = 4,096 values)
  • Place Value: Convert binary to decimal by summing bit × 2position
  • Floating Point: IEEE 754 representation allows efficient storage of very large/small numbers
  • Precision Pitfalls: Never use == for float comparison; use threshold-based comparison

Understanding binary is essential for interpreting ADC values, calculating memory requirements, and debugging sensor data in IoT systems.

Key Takeaway

Binary is the universal language of digital systems. Every sensor reading in IoT passes through a binary representation, and the number of bits (resolution) directly determines how precisely a real-world measurement can be captured. Understanding binary, powers of 2, and floating-point limitations is essential for correctly interpreting sensor data and avoiding subtle bugs in IoT applications.

Common Pitfalls

Most sensors transmit 16-bit values as two separate bytes. Some sensors are big-endian (high byte first) while others are little-endian (low byte first). Combining bytes in the wrong order produces a completely wrong value — for example, reading a temperature of 25.3 C as 19987.4 C because high and low bytes were swapped. Always check the datasheet for byte order and combine accordingly: value = (high << 8) | low for big-endian.

Accelerometer Z-axis at 0 g returns 0x0000; at +2 g returns approximately 0x4000; at -2 g returns 0xC000 (in two’s complement, this is -16384). Casting 0xC000 to an unsigned integer gives 49152 instead of -16384. Always cast signed sensor data to the appropriate signed integer type before arithmetic operations.

Summing 100 ADC readings (0-4095 each) into a 16-bit unsigned integer (max 65535) risks overflow if values are near maximum: 100 x 4095 = 409500, which overflows a 16-bit integer. Use 32-bit integers (uint32_t) for accumulation before dividing to compute the average.

Left shift (<<) multiplies by powers of 2 and fills with zeros on the right; right shift (>>) divides by powers of 2 but fills with the sign bit for signed values (arithmetic shift) or zeros (logical shift) depending on the data type. Shifting a signed value right in C can produce unexpected results if the variable type is not explicitly specified as unsigned.

15.9 What’s Next?

Now that you can convert between binary and decimal and recognise floating-point precision pitfalls, explore how ADCs apply these concepts to real sensor voltages.

Chapter Focus
ADC Fundamentals How ADCs convert analog voltages to digital values using the binary principles covered here
Nyquist Sampling Theory Minimum sampling rates required to faithfully capture analog signals
ADC/DAC Worked Examples Hands-on calculations combining binary, resolution, and voltage scaling
DAC and PWM Output Converting digital values back to analog signals for actuator control
Data Representation How binary sensor values are encoded and transmitted as network packets
Electricity Fundamentals Voltage, current, and resistance – the signals that ADCs digitise