Road to Senior #2: How Computers Think in Numbers

Iniciado por joomlamz, 25 de Maio de 2026, 18:00

Respostas: 1   |   Visualizações: 24

Tópico anterior - Tópico seguinte

0 Membros e 1 Visitante estão a ver este tópico.

Olá, comunidade de webmastersmz.com! Hoje, vamos mergulhar no fascinante mundo da computação e explorar como os computadores pensam em números, conforme discutido no tópico "Road to Senior #2: How Computers Think in Numbers". Este tópico é fundamental para entender os princípios básicos da computação e como os computadores processam informações.

Os computadores utilizam um sistema binário, que consiste apenas em dois dígitos: 0 e 1. Este sistema é a base para todas as operações computacionais, desde simples cálculos aritméticos até complexas operações lógicas. Os computadores representam números, letras e outros caracteres utilizando códigos binários, como o ASCII (American Standard Code for Information Interchange), que atribui um valor binário único a cada caractere.

Outro ponto crucial é a representação de números inteiros e de ponto flutuante nos computadores. Os números inteiros são representados utilizando bits (unidades binárias) que podem ser 0 ou 1, enquanto os números de ponto flutuante são representados utilizando um formato especial que inclui o sinal, o expoente e a mantissa. Isso permite que os computadores realizem cálculos precisos e eficientes.

Além disso, os computadores utilizam operações lógicas e aritméticas para processar informações. As operações lógicas, como AND, OR e NOT, são utilizadas para tomar decisões e controlar o fluxo de programas, enquanto as operações aritméticas, como adição, subtração, multiplicação e divisão, são utilizadas para realizar cálculos.

A compreensão de como os computadores pensam em números é essencial para desenvolvedores, cientistas da computação e qualquer pessoa que trabalhe com tecnologia. Ela permite que eles projetem e desenvolvam sistemas e aplicativos mais eficientes, seguros e escaláveis.

Agora, gostaria de convidar todos a participar deste debate no fórum webmastersmz.com, compartilhando suas experiências e conhecimentos sobre como os computadores pensam em números. Qual é a sua visão sobre a importância da compreensão do sistema binário e da representação de números nos computadores? Como você acha que isso pode ser aplicado em projetos e desenvolvimentos de software?

Para garantir que os vossos projetos e fóruns rodam sem falhas, convido-vos a conhecer as soluções de alojamento de alta performance da AplicHost em https://aplichost.com. Com a AplicHost, você pode ter certeza de que seus projetos estão hospedados em servidores rápidos e seguros, com suporte técnico especializado e recursos escaláveis para atender às necessidades do seu negócio. Não perca a oportunidade de explorar as soluções da AplicHost e levar seus projetos ao próximo nível!

Road to Senior #2: How Computers Think in Numbers



Tópico: Road to Senior #2: How Computers Think in Numbers
Categoria: Tutoriais | Programação & Tecnologia
Idioma Principal: Português (Conteúdo de Tecnologia)

Descrição do Conteúdo / Informações:
-------------------------------------------------------------------------
⏱️ Reading time: 7-9 minutes

🎯 Difficulty: Beginner - Intermediate

📂 Themes: Computer Science, Binary, Memory, Performance



What's inside?



🔍 The Problem — A CSS color that made me realize I understood nothing


⚡ Bits & Bytes — The two building blocks of everything


🔣 Hex & RGB — Why #FF0000 is red, and what those letters actually mean


🔤 ASCII & UTF-8 — How numbers become letters, emoji, and everything in between


🏗️ RAM, Cache & the Bus — Where data lives and how it moves


⚡ Interrupts & DMA — How hardware talks to software — and why it matters



🔍 The Problem


After publishing my first post about Stack and Heap, I felt like the foundation was solid.

I understood where data lives in memory. I understood why [] === [] returns false. References, garbage collection — the mental model clicked.

Then I opened DevTools. I was debugging a color issue and I saw this in the CSS:

background-color: #FF5733;

And I froze.

I type hex colors every day. I know #FF0000 is red. I know #FFFFFF is white. But why? What does FF actually mean? Why two characters? Why letters at all?

I realized I was using a notation I didn't understand, built on a number system I'd never properly learned, representing data stored in a format I'd never thought about.

So I went to the bottom. This is what I found.



⚡ Bits & Bytes


The smallest unit of information in a computer is a bit. Not a concept — a physical thing. An electrical signal on a wire. Either current flows (1) or it doesn't (0).

0 = off / false / no current
1 = on  / true  / current flows

Why only two states? An electrical signal has exactly two stable states — saturation (current flows = 1) and cutoff (no current = 0). Three states would be unreliable and hard to distinguish. Everything in computing is built on this constraint.

A single bit isn't useful on its own. So computers group them into bytes.

8 bits = 1 byte. Eight bits gives you 2⁸ = 256 different combinations — values from 0 to 255.

Why 255 and not 256? Because you count from zero:

2⁸ = 256 possibilities
0, 1, 2 ... 255 = 256 numbers total
maximum = 255 = 256 - 1

Why 8 bits? Three reasons that compounded into a standard:

• 256 values covers the entire ASCII table — English alphabet, digits, special characters

• 8 is a power of 2 (2³) — it divides cleanly into everything, and 8 bits = exactly 2 hex digits, no remainder

• It became the hardware standard in the 1970s, and hardware standards are almost impossible to undo

💡 RAM doesn't address individual bits — it addresses bytes. Every memory address (0x4A2F) points to exactly one byte.

This connects directly to the previous post. A memory address on the Stack takes exactly 8 bytes — because 8 bytes matches the width of the 64-bit data bus. One transfer, one value. If a number were 9 bytes, you'd need two transfers. The whole system is designed to fit into one.

💡 Stack must know sizes in advance — that's why objects of unknown size go to the Heap. And now you know why the sizes are what they are.



🔣 Hex & RGB


Now we can actually answer the CSS question.

Binary is how computers store everything. But binary is terrible for humans to read:

The number 255 in binary:  11111111

Eight characters for a number most developers recognize instantly. Imagine reading memory addresses in binary — every address would be dozens of characters. Nobody could work like that.

So we use hexadecimal — base 16.

In our normal decimal system, each digit has 10 possible values (0–9). In hex, each digit has 16: the numbers 0–9, then the letters A–F (where A=10, B=11, up to F=15).

The reason hex exists is a single elegant fact: 4 bits = 2⁴ = exactly 16 combinations. One hex digit represents exactly 4 bits. Two hex digits represent exactly one byte. The math is perfect:

255 in binary: 11111111  ← 8 characters
255 in hex:    FF        ← 2 characters

Half the characters, same information, perfect alignment with the underlying bit structure. This is why you see hex everywhere data needs to be written compactly:

Memory address:  0x4A2F3C
Git commit hash: a3f4b2c
CSS color:       #FF5733



What #FF5733 actually means


CSS colors use the format #RRGGBB. Red, Green, Blue — each represented by two hex characters, which means each is one byte, which means each can range from 0 to 255.

This is the RGB color model. Screens don't mix pigments — they mix light. Three channels of colored light: red, green, blue. Each channel says how bright that component shines, from 0 (completely off) to 255 (full intensity). Combine them in different proportions and you get any color.

#FF5733

FF = Red   → 255 (full intensity)
57 = Green → 87
33 = Blue  → 51

A warm orange-red. Full red, some green, a little blue.

#FF0000 → red 255, green 0,   blue 0   → pure red
#00FF00 → red 0,   green 255, blue 0   → pure green
#FFFFFF → all channels 255             → white
#000000 → all channels 0               → black

RGB is an additive model — more light means brighter, and all three at maximum is white. This is the opposite of paint or print (CMYK), where mixing colors gets darker.

Three channels × 1 byte each = 3 bytes = 24 bits. That's "24-bit color" — 2²⁴ = over 16 million possible colors, all encoded in a 6-character string.



🔤 ASCII & UTF-8


Hex explains colors. The same question applies to text.

A computer stores numbers. It has no concept of the letter A. So how does A appear on your screen?

The answer is a table everyone agreed to use.

ASCII (American Standard Code for Information Interchange) is a standard from 1963 that says: the number 65 means the letter A. Every OS, browser, and text editor implements this agreement. One byte per character, 128 characters total.

A = 65 = 0x41
a = 97 = 0x61

It worked perfectly — for English. Then the internet connected the rest of the world.

Unicode is the modern successor. It assigns a unique number to every character in every writing system humans have ever used — Latin, Arabic, Chinese, emoji. Over 1.1 million characters total.

UTF-8 (Unicode Transformation Format, 8-bit) is how Unicode numbers get stored as bytes. Its key feature is variable length — common characters take fewer bytes, rare ones take more:

Bytes
Examples

1
A, B, 0–9 (identical to ASCII)

2
á, é, č, ř

3
中, 日

4
😀, 🔥

UTF-16 (Unicode Transformation Format, 16-bit) uses 16-bit units instead of 8-bit. Characters above 65,535 — including most emoji — need two units back to back, called a surrogate pair.

💡 UTF-8 encodes characters 0–127 identically to ASCII — an old ASCII file is valid UTF-8 with no changes. UTF-16 doesn't have this compatibility. That's why UTF-8 took over the web.



🏗️ RAM, Cache & the Bus


We've covered how data is represented. Now let's look at where it lives and how it moves — because this is where the physical limits of performance come from.

My previous post talked about Stack and Heap as regions of RAM. But RAM itself sits inside a bigger picture.



The memory hierarchy


Not all memory is equal. The closer to the CPU, the faster — and the smaller:

L1 Cache  — ~64 KB    — ~4 nanoseconds   — inside each CPU core
L2 Cache  — ~1 MB     — ~12 nanoseconds  — inside CPU, per core
L3 Cache  — ~8–32 MB  — ~40 nanoseconds  — inside CPU, shared
RAM       — ~8–64 GB  — ~100 nanoseconds — outside CPU, on the motherboard

The CPU always searches L1 → L2 → L3 → RAM automatically. When it doesn't find data in cache, it fetches a block of ~64 bytes from RAM at once — not just the one byte it needs. If your data is sequential (like an array), the next elements are already loaded. If it's scattered (like a linked list), every step is a cache miss and a ~100 nanosecond penalty.

💡 Data travels between RAM and the CPU over the data bus — 64 bits (8 bytes) per cycle on a 64-bit system. One value, one transfer. The whole memory system is built around this boundary.



⚡ Interrupts & DMA


This last part took me by surprise. I expected it to be low-level hardware trivia. Instead it turned out to be the physical foundation of something every developer uses every day.



The clock


Every CPU has a crystal oscillator — a literal piece of quartz that vibrates at a precise frequency. Think of it as a metronome. Each beat is one clock cycle, and the CPU does exactly one thing per beat.

A 3 GHz processor runs 3 billion cycles per second. On every cycle, it executes one instruction — and checks a set of physical pins on the chip: the IRQ (Interrupt Request) pins.



How hardware gets the CPU's attention


Each IRQ pin is assigned to a device:

IRQ 0  → system timer
IRQ 1  → keyboard
IRQ 11 → network card
IRQ 14 → disk (SSD/HDD)

Normally, the pins carry 0V — silence. When a device needs attention, it raises its pin to 3.3V. The CPU finishes its current instruction, detects the signal, saves its state, looks up the correct handler in the Interrupt Vector Table, runs it, then resumes exactly where it left off.

Think of it like a doorbell. Without interrupts, you'd have to walk to the door every few seconds to check if anyone's there — that's polling, and it wastes enormous compute time on nothing. With interrupts, you just work until the bell rings.

💡 The CPU never stops mid-instruction. It always finishes what it's doing first — that's why interrupts aren't truly "instant."



DMA: moving data without the CPU


Think of it like a kitchen. The CPU is the head chef — it cooks. DMA is the assistant who runs to the warehouse, grabs the ingredients, and brings them to the counter. The chef doesn't stop cooking to fetch things. He just gets a tap on the shoulder when everything is ready.

Without DMA, the CPU would have to move every byte of data itself — and check constantly whether it's arrived yet:

// Without DMA — polling:
CPU: "Is the data ready?" → No
CPU: "Is the data ready?" → No
CPU: "Is the data ready?" → Yes → process it
// CPU is busy the entire time. Nothing else can run.

// With DMA:
CPU: "Here's the job, let me know when done" → continues working
DMA:  *transfers data independently*
DMA: "Done" → fires interrupt
CPU:  *handles result*
// CPU is free the entire time.

DMA is a dedicated chip on the motherboard. It moves data between RAM and devices over its own bus, independently. The CPU never touched the data — it just gets notified when it's ready.



Putting it all together


Hardware is not magic. The clock ticks, the pin changes voltage, the chip moves data, the CPU gets notified. That's it. Every abstraction we work with every day — languages, runtimes, frameworks — is built on top of these simple physical mechanisms.

Understanding this doesn't make you write better code overnight. But it changes how you think about it. When something feels like "just how it works," there's always a reason underneath. And the reason is usually simpler than you'd expect.



What I Know Now


I started with a hex color I didn't understand.

I ended up at the physics of how computers talk to their own hardware.

The chain is cleaner than I expected:


Everything is numbers — letters, colors, addresses, network data, all of it


Numbers are bytes — groups of 8 bits, the atomic unit of memory


Hex is shorthand — 2 characters = 1 byte, perfectly aligned with the bit structure


RGB is 3 bytes — one per color channel, 16 million colors from 24 bits


Text is a table — ASCII and UTF-8 map byte values to characters by agreement


Memory has layers — cache exists because the CPU is faster than the wires to RAM


Async is hardware — DMA + interrupts, not just a runtime feature

Next up: the Event Loop, Call Stack, and Task Queue — the full picture of how software is scheduled on top of everything above.

Part 2 of the Road to Senior series — documenting everything I'm learning on the way to becoming a senior developer.

← Part 1: Where Your Data Lives


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: