TRANSCRIPCIÓN · CC BY 4.0

Cómo funciona una computadora: del silicio y las compuertas NAND a la RAM y las aplicaciones

Título original en inglés: How a Computer Works - from silicon to apps

Improbable Matter · Publicado el · 43 min · Audio original en inglés · subtítulos en español · Licencia: CC BY 4.0 · Fuente: ver en YouTube

Esta ficha ofrece el título y el contexto en español junto con la transcripción original íntegra en inglés con marcas de tiempo. Pulsa el botón superior para abrir la vista bilingüe español-inglés sincronizada en el lector.

Resumen generado por IA

Este vídeo ofrece una visión general deliberadamente simplificada y desde cero de cómo funciona un ordenador, con cada sección terminando en un resumen y explicaciones adicionales enlazadas en la descripción; el ponente señala que probablemente nadie conoce todos los matices de cómo se construye y opera un ordenador, y una señal sonora de la 5ª sinfonía de Beethoven advierte que se aplican simplificaciones masivas en todo el vídeo. Parte de un circuito de batería-interruptor-bombilla y del voltaje binario encendido/apagado, presenta el MOSFET como un interruptor controlado por voltaje (el canal N conduce con voltaje de puerta alto, el canal P lo contrario), y los empareja como CMOS para producir salidas invertidas que se dice forman la base de todos los procesadores modernos. La fabricación a partir de silicio dopado, litografía, deposición y grabado construye miles de millones de transistores en una oblea dopada con P. Se explican el álgebra booleana y las puertas (NOT, OR, AND, XOR, NAND), describiéndose la NAND como universal; las puertas implementan aritmética binaria, desplazamientos de bits, comprobaciones de igualdad y almacenamiento mediante biestables D y registros, sincronizados por un reloj. El vídeo cubre después la jerarquía de memoria (registros, caché, RAM, disco duro), las direcciones de 32 bits frente a 64 bits, la arquitectura von Neumann con instrucciones almacenadas como números binarios, y las instrucciones de salto que permiten bucles y ramificación condicional para la completitud de Turing. También se describen los lenguajes de alto nivel y compiladores, las bibliotecas compartidas, las pantallas LED y los píxeles, el trazado de líneas de Bresenham, el sonido mediante una tarjeta de sonido, y las entradas de teclado y ratón.

Resumen traducido automáticamente con IA a partir de la transcripción. Comprueba los fragmentos enlazados con el vídeo original.

Resúmenes por capítulo con marcas de tiempo

Cómo funciona un ordenador: una visión general desde cero

Alcance y enfoque de la visión general

  • [0:10] El vídeo pretende ofrecer una visión general amplia de cómo funciona un ordenador desde cero, adentrándose algo en lo técnico mientras mantiene las cosas lo más simples posible.
  • [0:22] Cada sección termina con un resumen, y en la descripción se enlazan explicaciones adicionales.
  • [0:32] El ponente señala que probablemente nadie conoce todos los matices de cómo se construye y opera un ordenador.
  • [0:37] Una señal sonora de la 5ª sinfonía de Beethoven advierte que se están haciendo simplificaciones masivas, y esta advertencia se aplica a todo el vídeo.

Los transistores como interruptores controlados por voltaje

Circuitos básicos y estados de voltaje binarios

  • [1:04] Un circuito simple puede consistir en una batería conectada a través de un interruptor y una bombilla de vuelta al terminal negativo de la batería.
  • [1:13] Los componentes de los ordenadores modernos suelen suministrar 3,3 o 5 voltios entre el terminal positivo y tierra o el terminal negativo.
  • [1:24] Los ordenadores tratan la información como binaria —encendido o apagado, verdadero o falso, uno o cero— según si el voltaje es alto o bajo.

Interruptores de pulsación: de contacto frente a de corte

  • [1:35] El componente clave en el circuito de ejemplo es el interruptor de pulsación, que se presenta en dos variantes.
  • [1:37] Un interruptor de contacto cierra el circuito entre sus dos terminales cuando una persona lo pulsa, encendiendo la bombilla.
  • [1:43] Un interruptor de apertura por presión hace exactamente lo contrario.

Terminales del MOSFET y tipos de canal

  • [1:48] El símbolo del transistor mostrado es específicamente un transistor de efecto de campo de óxido metálico y semiconductor, o MOSFET.
  • [1:56] La fuente y el drenaje de un MOSFET actúan como los dos terminales de un interruptor, pero tiene un tercer terminal llamado puerta.
  • [2:05] El tipo de canal N cierra un circuito cuando se aplica un alto voltaje a la puerta, como un interruptor de cierre por presión, mientras que el de canal P abre el circuito cuando se aplica un alto voltaje, como un interruptor de apertura por presión.
  • [2:19] Así, los transistores actúan como interruptores, excepto que se aplica un voltaje en lugar de que una persona los presione.

Pares CMOS y el circuito inversor

  • [2:24] Las computadoras modernas usan estos transistores en pares denominados CMOS, o semiconductor de óxido metálico complementario, con los terminales de puerta de un par siempre conectados entre sí para recibir la misma entrada.
  • [2:39] Con un alto voltaje o 1 en la entrada, el MOSFET de canal N abre una ruta entre el alto voltaje y la salida, mientras que el de canal P cierra la ruta a tierra.
  • [2:52] Con un bajo voltaje o 0 en la entrada, el canal P abre un camino a tierra.
  • [2:58] Esa primera disposición parece inútil porque la salida coincide con la entrada, pero intercambiar los dos MOSFET hace que una entrada alta abra una ruta hacia el bajo voltaje o 0 y que una entrada 0 produzca un 1 en la salida.
  • [3:17] Sea lo que sea que se ponga en la entrada, lo opuesto aparece en la salida, y se dice que esto forma la base de todos los procesadores modernos.

Cómo se fabrican los transistores y chips CMOS

Dopaje del silicio para crear regiones de tipo P y tipo N

  • [3:40] El silicio es un semiconductor con cuatro electrones de valencia que se dopa, o mezcla, con otros elementos.
  • [3:47] El galio tiene tres electrones de valencia, uno menos que el silicio, lo que hace que la región sea más positiva o de tipo P.
  • [3:54] El arsénico tiene cinco electrones de valencia, uno más que el silicio, lo que añade una carga negativa y hace que la región sea de tipo N.
  • [4:03] Cantidades traza de estos dopantes, típicamente alrededor de uno por millón de átomos de silicio, se implantan mediante difusión química o disparándolos desde un acelerador de partículas.

Estructura del transistor de efecto de campo y del MOSFET

  • [4:14] Los transistores se fabrican intercalando una región de un dopante entre dos regiones del otro, y se examina más de cerca la configuración de canal N.
  • [4:22] La configuración de canal N no conduce por sí misma, pero un campo eléctrico aplicado forma un canal conductor, de ahí el nombre de transistor de efecto de campo.
  • [4:31] Esto puede concebirse como el campo eléctrico que atrae electrones desde la región dopada con N, que tiene un exceso, hacia la región dopada con P, que tiene un déficit.
  • [4:44] Un terminal conductor cerca de la pila de semiconductores forma un campo eléctrico a alto voltaje y hace que el transistor conduzca, pero se necesita una capa aislante para evitar un cortocircuito.
  • [4:53] El contacto es metal, el aislante es óxido de silicio y el semiconductor dopado completa la pila, de ahí el término MOSFET.

Litografía: deposición y grabado sobre el dado

  • [5:03] Un ordenador necesita millones de pares CMOS interconectados que sean pequeños y estén próximos entre sí para que las señales eléctricas viajen rápidamente entre ellos.
  • [5:13] La fabricación de procesadores suele comenzar con un bloque sólido de silicio dopado con P llamado dado, sobre el cual se crean transistores mediante litografía, que significa "escritura sobre piedra".
  • [5:29] La deposición acumula químicamente una capa de espesor controlado y predeterminado en todo el dado, por ejemplo recubriendo el dado dopado con P con silicio dopado con N.
  • [5:43] El grabado elimina el material superficial no deseado aplicando productos químicos o plasma caliente sobre la parte superior del dado, con varias etapas que garantizan que el material se elimine de forma selectiva.

Enmascaramiento con fotorresistente y grabado selectivo

  • [6:02] Un producto químico llamado fotorresistente se deposita sobre el dado y se hace pasar luz a través de una máscara para exponer áreas predeterminadas.
  • [6:12] Las áreas expuestas deben ser del mismo tamaño o mayores que la longitud de onda de la luz utilizada, por lo que para la litografía se emplea luz ultravioleta de longitud de onda muy corta.
  • [6:23] Un método de grabado elimina solo las regiones expuestas del fotorresistente, abriendo huecos, y luego otro método de grabado ataca todo excepto el fotorresistente no expuesto.
  • [6:39] Finalmente se elimina por grabado el fotorresistente restante, de modo que se ha retirado material dondequiera que haya huecos en la máscara.

Construcción y conexión de todos los transistores simultáneamente

  • [6:48] La deposición y el grabado usados conjuntamente implican que los dopantes de tipo N para todos los transistores del dado pueden añadirse simultáneamente.
  • [6:58] A continuación se deposita y se graba óxido de silicio y, por último, se deposita metal y se elimina por grabado para dejar canales metálicos sobre el dado.
  • [7:06] Estas estructuras metálicas forman no solo los terminales conductores de los transistores, sino también las pistas equivalentes a cables que conectan los transistores según sea necesario.
  • [7:16] Cada ciclo deposita fotorresistente, lo expone a través de una máscara, crea huecos y graba el dado, y mediante este método se ensamblan y conectan entre sí miles de millones de transistores.

Cómo los ordenadores representan y procesan la información

Representación binaria mediante estados de voltaje

  • [7:40] Los ordenadores manejan la información como unos y ceros, que corresponden a un voltaje alto o bajo en un circuito eléctrico.

Transistores como conmutadores complementarios

  • [7:48] Los transistores actúan como conmutadores electrónicos que cambian entre los dos estados de voltaje.
  • [7:52] Los transistores siempre vienen en pares complementarios, de modo que cuando una mitad del par se abre, la otra se cierra.

Litografía para construir circuitos de transistores

  • [7:58] La litografía es el proceso mediante el cual se construyen grandes cantidades de transistores interconectados sobre un bloque de silicio.

Puertas lógicas booleanas e implementación CMOS

Álgebra booleana y puertas de una sola entrada

  • [8:10] El álgebra booleana es la rama de la lógica matemática que explica por qué las redes de transistores son útiles, ilustrado aquí con ejemplos desenfadados.
  • [8:28] En un ejemplo de restaurante, Alice está feliz cuando se sirven hamburguesas, mientras que Bob está feliz cuando no se sirven.
  • [8:36] Una puerta toma una entrada binaria (verdadero o falso, 1 o 0) y devuelve una salida binaria; aquí la entrada es si se sirven hamburguesas y la salida es si alguien está feliz.
  • [8:54] La puerta de Alice simplemente emite el mismo valor que su entrada, lo que en términos electrónicos es solo una conexión, mientras que la puerta de Bob es una puerta NOT, mostrada con su símbolo habitual.

Puertas de múltiples entradas: OR, AND y XOR

  • [9:14] Las puertas pueden tener múltiples entradas, y sus nombres son sencillos.
  • [9:22] Con pizza y fideos como opciones, Alice está feliz si se sirve al menos uno o ambos, lo cual es una puerta OR.
  • [9:35] Bob quiere tanto pizza como fideos en el menú, lo cual es una puerta AND.
  • [9:42] Charlie está feliz si se sirven pizza o fideos pero no ambos, ya que piensa que un restaurante no lo suficientemente especializado no haría un buen trabajo; esta es la puerta de or exclusivo, o XOR.

Puertas complementarias y comportamiento NAND

  • [9:53] Cada puerta tiene una versión complementaria, esencialmente la misma puerta seguida de una puerta NOT, denotada por el símbolo habitual con un círculo en la salida.
  • [10:01] La puerta NAND emite 0 cuando todas sus entradas son 1 y emite 1 en caso contrario.
  • [10:12] Para una computadora, estas y todas las demás puertas posibles deben implementarse mediante pares CMOS.

Construcción y universalidad de la NAND CMOS

  • [10:18] Conectar dos pares CMOS como se muestra crea una puerta NAND, con transistores de canal N y de canal P que siguen trabajando en pares.
  • [10:26] Solo cuando se aplica un voltaje alto o 1 a ambos pares de entradas se cierran los caminos hacia el voltaje alto y se abre el camino a tierra, emitiendo un 0, que es exactamente el comportamiento NAND.
  • [10:40] La puerta NAND es universal: cualquier otra puerta puede crearse a partir de puertas NAND siempre que haya suficientes, aunque existen formas más eficientes de fabricar ciertas puertas.
  • [10:48] En esencia, esto significa que el problema de implementar puertas lógicas mediante pares CMOS está resuelto.

Puertas con más de dos entradas

  • [10:56] Las puertas pueden tener tres, cuatro o tantas entradas como sea necesario.
  • [11:00] Por ejemplo, dos puertas AND conectadas como se muestra simplemente se convierten en una puerta AND de tres entradas, y así sucesivamente.

Puertas lógicas e implementación CMOS

Definición de puertas lógicas

  • [11:10] Las puertas lógicas son objetos matemáticos conceptuales que permiten deducciones basadas en enunciados binarios verdaderos o falsos.
  • [11:18] Por ejemplo, si es verdad que hoy es sábado o hoy es domingo, entonces también es verdad que hoy es fin de semana.

Implementación práctica con pares CMOS

  • [11:24] Los pares CMOS de la sección anterior pueden usarse para implementar prácticamente estas puertas en términos de lógica binaria electrónica.

Puertas lógicas y aritmética binaria en computadoras

Representación en base 2 y pistas de bits

  • [11:39] Las computadoras manejan números y usan redes de puertas lógicas para realizar aritmética.
  • [11:46] La base 10 usa los dígitos 0–9 que representan múltiplos de potencias de 10 (1, 10, 100, 1000), mientras que las computadoras modernas usan base 2 con los dígitos 0 y 1 que representan potencias de 2 (1, 2, 4, 8).
  • [12:10] En base 10, 953 equivale a 9×100 + 5×10 + 3×1; en binario, 101 equivale a 1×4 + 0×2 + 1×1, que es 5 en base 10, y cualquier número en base 10 puede representarse en base 2 y viceversa.
  • [12:28] El número binario 101 puede representarse mediante tres pistas eléctricas con voltajes encendido, apagado, encendido; cada pista porta un bit, por lo que tres pistas forman un número de 3 bits, y los números de 4 bits y 8 bits se definen de forma similar.
  • [12:48] El número de 4 bits 0101 equivale al número de 3 bits 101.

Suma de números de 1 bit con XOR y AND

  • [12:56] Sumar los números de 1 bit A y B da 0+0=0 y 0+1=1, mientras que 1+1 requiere escribir 0 y llevar 1, tal como hace 5+5 en base 10.
  • [13:18] Para almacenar el resultado para cualquier valor posible de A y B, C debe ser un número de 2 bits.
  • [13:26] El bit derecho de C es 1 cuando A o B es 1 pero no ambos, que es el comportamiento de la puerta XOR, y el bit izquierdo es 1 solo si A y B son ambos 1, que es el comportamiento de la puerta AND.
  • [13:51] Sumar números mayores que 1 bit es más complicado porque se necesitan puertas de tres entradas para un bit de A, un bit de B y un bit acarreado; las puertas NAND son universales, por lo que cualquier red de puertas requerida puede implementarse con suficientes de ellas.

Multiplicación binaria mediante desplazamiento de bits

  • [14:20] En base 2, multiplicar por 10 (binario) o 2 (base 10) solo añade un 0 al final, por lo que multiplicar por 10, 100 o 1000 en binario desplaza cada bit a la izquierda y añade un 0, lo que se llama desplazamiento de bits.
  • [14:44] Multiplicar por un número arbitrario como 11 en binario es lo mismo que multiplicar por 10 y por 1 y sumar ambos resultados.
  • [14:53] La multiplicación binaria de A por un B arbitrario funciona comenzando con cero, sumando A si el bit más a la derecha de B es 1, luego desplazando A una vez y sumándolo al total si el siguiente bit de B es 1, continuando para cada bit de B.

Comparación de igualdad con XNOR y AND

  • [15:11] Las computadoras dependen de comparaciones como si A es igual a B o si A es mayor que B, por ejemplo comparando una hora actual en segundos almacenada como binario A contra una hora de alarma almacenada como B.
  • [15:30] Para comprobar la igualdad, la computadora debe verificar que cada bit de A coincida con el bit correspondiente de B; XOR devuelve 1 cuando sus entradas difieren, y XNOR, su complemento, devuelve 1 cuando sus entradas son iguales.
  • [15:50] Un conjunto de puertas XNOR aplicadas a cada par de bits de A y B indica si esos bits son iguales, y aplicar una puerta AND a las salidas XNOR devuelve un solo bit que es 1 si y solo si A es igual a B.

Otras operaciones y alcance numérico

  • [16:08] La resta, la división y otras comparaciones también pueden implementarse con redes de puertas; por ejemplo, desplazar bits en la otra dirección divide un número entre dos, y todas estas se implementan usando transistores grabados en un chip.
  • [16:20] En este video, "número" se refiere a un entero o número completo; las fracciones pueden almacenarse en una versión binaria de la notación científica llamada números de punto flotante o floats, cuyo principio general sigue aplicándose aunque su funcionamiento no se cubre.
  • [16:36] En resumen, las computadoras usan secuencias de señales eléctricas binarias de encendido/apagado para representar números en base 2 en lugar de la base 10 que las personas usan a diario, y las redes de puertas lógicas pueden sumar, restar y comparar números binarios, con unos pocos pasos adicionales que permiten la multiplicación y la división.

División y composición de circuitos

División de circuitos

  • [16:53] El orador afirma que estos elementos también deben dividirse.

Composición de circuitos

  • [17:00] El orador señala que ya se han examinado los circuitos compuestos por ciertos componentes.

Bits, bytes y representación de números con signo

Ancho de bits fijo en las computadoras comerciales

  • [17:01] Los transistores pueden implementar la suma y otras operaciones algebraicas para números con dígitos binarios o bits arbitrarios.
  • [17:09] Construir una computadora requiere elegir exactamente cuántas pistas eléctricas y puertas están disponibles para representar un número, de forma similar a un formulario con un número fijo de casillas impresas para la edad.
  • [17:22] En las computadoras comerciales este número siempre es un múltiplo de 8, y 8 bits se denominan un byte.
  • [17:27] Los circuitos sumadores toman como entradas números de 1 byte (8 bits), 2 bytes (16 bits) o 4 bytes (32 bits).

Convención del bit de signo

  • [17:40] Independientemente de cuántos bytes comprenda un número, uno de sus bits puede reservarse para denotar un signo más o menos.
  • [17:47] Cuando un número tiene signo de esta manera, un bit inicial de 0 significa que el número es positivo y un bit inicial de 1 significa que es negativo.

Almacenamiento de entradas y salidas

  • [17:55] Como en un examen de matemáticas, es importante guardar tus cálculos.
  • [18:00] Cualquiera que sea la operación que realice una computadora, las entradas y las salidas deben almacenarse de alguna manera.

Latches, registros y sincronización de reloj

Circuitos latch y almacenamiento de datos

  • [18:06] Un latch es un circuito que, una vez bloqueado, permanece en ese estado durante mucho tiempo y, por lo tanto, puede almacenar un bit de datos; 8 latches almacenan un byte.
  • [18:18] Un latch D construido con puertas NAND tiene una salida que se realimenta a una entrada, y esta interconexión permite que la red de puertas mantenga y retenga su valor de salida de 0 o 1.
  • [18:44] Nada cambia a menos que la entrada E o de habilitación sea 1; cuando la habilitación es 1, el bit que se aplique a D se propaga a la salida.

Registros en un circuito sumador

  • [18:55] La computadora realiza una operación como la suma, habilita los circuitos de latch para almacenar la salida y luego vuelve a desactivar la habilitación para que el resultado se mantenga el tiempo necesario.
  • [19:07] 8 latches pueden formar un registro que almacena un byte de datos durante el tiempo necesario.
  • [19:11] Un circuito sumador tendría registros para almacenar las entradas antes de la suma y un registro para capturar el resultado.

Ciclos de reloj y sincronización

  • [19:23] Debido a que las señales eléctricas tardan un tiempo pequeño pero significativo en propagarse y los transistores en terminar de conmutar, todas las computadoras tienen un reloj para garantizar que una operación se realice por completo antes de leer la respuesta.
  • [19:36] Un cristal oscilante conmuta el voltaje entre encendido y apagado a una velocidad muy específica; en la época del video, los procesadores tenían velocidades de reloj típicas de 2 gigahercios, o 2 mil millones de conmutaciones por segundo.
  • [19:55] Una suma completa requiere al menos 3 ciclos de reloj: los números se cargan en los registros de entrada en el primero, el circuito sumador trabaja durante el siguiente, y el registro de salida recibe una señal de habilitación y almacena el resultado en el tercero.
  • [20:18] La mayoría de las operaciones tardan mucho más que uno o incluso tres ciclos de reloj, como la multiplicación con varios pasos de suma, pero el reloj sigue sincronizando desde que comienza una operación hasta que la salida está lista.

Ubicación de la lógica aritmética

  • [20:38] Toda la llamada lógica aritmética, los arreglos de puertas lógicas que realizan sumas y restas, se ubica físicamente junto con el resto del procesador.

Memoria y almacenamiento en las computadoras

Registros y caché del procesador

  • [20:46] Los registros en un chip se denominan procesador o unidad central de procesamiento.
  • [20:51] Los circuitos llamados caché pueden almacenar hoy en día decenas de kilobytes de datos como etapas intermedias de los cálculos.

Almacenamiento por condensadores en la RAM

  • [21:01] Se necesita una forma mayor y de más largo plazo para almacenar muchos más bytes de los que pueden contener los registros y la caché.
  • [21:08] Las computadoras tienen chips físicos separados de memoria de acceso aleatorio o RAM que usan condensadores para almacenar datos.
  • [21:16] Un condensador cargado tiene un voltaje alto y un valor de 1, mientras que uno descargado tiene 0 voltios respecto a tierra y es 0.
  • [21:24] La carga se fuga con el tiempo, pero los circuitos de memoria la reponen mientras el ordenador esté encendido.

Capacidad y direccionamiento de la RAM

  • [21:31] Un portátil típico tiene decenas de gigabytes, o miles de millones de bytes, de RAM.
  • [21:37] Cada byte en la RAM tiene su propia dirección binaria, como un buzón en un bloque de apartamentos.
  • [21:44] Los transistores de la RAM forman redes de puertas que devuelven el byte almacenado en la dirección recibida del procesador.

Direcciones de 32 bits frente a 64 bits

  • [21:56] Hasta hace poco, los ordenadores solían tener no más de 4 gigabytes de RAM, por lo que las direcciones de memoria eran números de 32 bits.
  • [22:04] Los números de 32 bits llegan hasta poco más de 4 mil millones, lo que antes era suficiente.
  • [22:10] Cuando la RAM se hizo más grande, efectivamente no había suficientes direcciones, por lo que ahora se usan números de 64 bits para las direcciones de memoria.
  • [22:17] Esta es la diferencia entre los programas de 32 y 64 bits.

Ejemplo de monedero y discos duros

  • [22:22] En un videojuego, el juego lleva un registro de la dirección donde se almacena el total de la cartera.
  • [22:31] Encontrar ocho monedas más hace que el juego obtenga el número de la cartera de esa dirección, lo cargue junto con el número binario para 8 en registros, los sume y vuelva a guardar el resultado.
  • [22:50] Los ordenadores también almacenan grandes volúmenes de datos en el disco duro durante décadas seguidas.

Límites de memoria, almacenamiento y procesamiento de los ordenadores

Mecanismo de almacenamiento magnético del disco duro

  • [22:55] Un disco duro está cubierto de diminutos dominios magnéticos que apuntan hacia arriba o hacia abajo para representar 1 o 0, incluso sin alimentación.
  • [23:04] A medida que el disco gira, un cabezal sensor puede leer pasivamente la orientación de los imanes como bits o invertir activamente los dominios para escribir datos.
  • [23:15] Cada byte también tiene su propia dirección separada, y un portátil u ordenador personal puede almacenar cientos de gigabytes en un disco duro.
  • [23:23] Existen otras tecnologías como la memoria flash y los DVD, pero no se tratan aquí.

Límite de la velocidad de la luz y compensaciones de memoria

  • [23:29] El límite fundamental de la velocidad de operación es la velocidad de la luz, que recorre unos 15 centímetros o medio pie durante un ciclo de reloj típico, por lo que un ordenador más grande necesitaría múltiples ciclos para obtener datos.
  • [23:43] En la práctica, los transistores conmutan mucho más despacio que eso, y un disco duro tarda en acelerar y escanear para leer datos.
  • [23:54] La caché es pequeña pero de rápido acceso, la RAM almacena muchos más bytes pero tarda más en leerse, y el disco duro es el que más tarda pero almacena gran cantidad de datos casi permanentemente.
  • [24:04] Por lo tanto, existe una compensación entre la rapidez con la que se pueden recuperar los datos y la cantidad que se puede almacenar.

Modelo simplificado de memoria de un solo conjunto

  • [24:09] Durante el resto del video, la computadora se explica como si tuviera un único pool de memoria que puede leer instantáneamente, aunque en realidad las cosas son más complicadas.

Resumen de reloj, bytes, registros y direcciones

  • [24:26] Un reloj sincroniza las operaciones y garantiza tiempo suficiente para terminar una operación antes de comenzar otra.
  • [24:36] Las computadoras procesan números binarios en grupos de 8 bits llamados byte.
  • [24:41] Los registros almacenan números durante los cálculos, mientras que en otros momentos los números se almacenan en la caché, en la memoria de acceso aleatorio y en un disco duro.
  • [24:49] Cada byte en la memoria tiene su propia dirección única, que a su vez es un número binario.

Necesidad de control de las operaciones

  • [25:02] Se implementan las operaciones binarias y el almacenamiento de resultados, pero la computadora aún necesita una forma de determinar algo más.

Instrucciones y ejecución de programas en memoria

Codificación de instrucciones y arquitectura de von Neumann

  • [25:09] Una instrucción especifica qué operación usar y cuándo, como sumar dos números o copiar un número.
  • [25:16] En la arquitectura de von Neumann, las instrucciones se almacenan en memoria como números binarios junto con otros datos.
  • [25:25] Por ejemplo, la instrucción número 16 en base 10, o un byte dado en binario, podría significar sumar dos números de 8 bits y almacenar el resultado, mientras que la instrucción 17 podría hacer lo mismo para números de 16 bits.
  • [25:41] Cuando la computadora encuentra una instrucción, un circuito de comparación activa el circuito lógico para la operación necesaria, como el circuito de suma cuando el byte es igual a 16.

Distinguir instrucciones por orden de bytes

  • [25:54] Un byte como 16 podría ser una instrucción de suma o un número de monedas en un videojuego, y la distinción depende del orden preciso en que los bytes aparecen en la memoria.
  • [26:05] El byte de instrucción va primero, seguido de las direcciones de memoria que necesita, como las dos direcciones de entrada y la dirección de salida para una suma.
  • [26:22] En los sistemas modernos de 64 bits las direcciones tienen 8 bytes de longitud, por lo que una instrucción de suma totaliza 25 bytes (un byte de instrucción más 24 bytes de direcciones), mientras que una instrucción de copia ocupa 17 bytes en total.
  • [26:45] Cada tipo de instrucción siempre ocupa un número fijo de bytes, y la siguiente instrucción sigue inmediatamente a la anterior.

Ejecución secuencial y consecuencias de errores

  • [26:54] Tras encontrar una instrucción de suma, la computadora la ejecuta y sabe que la siguiente instrucción está exactamente 25 bytes más adelante.
  • [27:01] La computadora interpreta inicialmente el byte número 0 al inicio de la memoria como una instrucción y a partir de ahí pasa de instrucción en instrucción.
  • [27:11] Si un error hace que la siguiente instrucción no esté donde debería, lo más probable es que la computadora se bloquee.

Ejecutar operaciones de suma y de múltiples bytes

  • [27:20] Para una suma, el número de la primera dirección se carga en un registro de entrada y el de la segunda dirección en otro, se habilita el circuito de suma y, tras suficientes ciclos de reloj, el resultado se escribe desde el registro de salida en la dirección de memoria requerida.
  • [27:38] Para sumar dos números de 16 bits, la computadora toma el byte en el número A más el inmediatamente siguiente, y hace lo mismo para el número B y el resultado C.

Ejemplo de programa: monedas en una cartera en un juego

  • [27:54] Un programa informático es una colección de instrucciones y direcciones que se ejecutan en orden, y el ordenador pasa de una instrucción a otra para ejecutarlo.
  • [28:13] En un ejemplo de juego, el byte 0 es una instrucción de suma seguida de la dirección del total del monedero, el número de monedas recién encontradas y de nuevo la dirección del monedero como salida, sobrescribiendo el total del monedero.
  • [28:26] El ordenador interpreta entonces el byte 25 como otra instrucción de suma, que añade al monedero las monedas obtenidas al vender objetos, y la siguiente instrucción está 25 bytes más adelante, en el byte 49.
  • [28:51] Como el total del monedero se usa mucho, probablemente se mantendrá a largo plazo tanto en la caché del procesador como en la RAM, y cuando el jugador guarde la partida se escribirá en un archivo de guardado en el disco duro.

Instrucciones de salto y condicionales para la completitud de Turing

Completitud de Turing y límites de instrucciones lineales

  • [29:36] Las instrucciones vistas hasta ahora funcionan de forma lineal —copiar un número, sumar dos—, por lo que el programa siempre produce el mismo resultado y finalmente llega al final de la memoria y se detiene.
  • [29:48] Se necesitan algunas instrucciones más para que un ordenador sea completo de Turing, es decir, que pueda llevar a cabo con el tiempo cualquier cálculo posible, como cargar una página web o renderizar un videojuego.
  • [30:01] La única diferencia entre dos ordenadores completos de Turing es la velocidad con la que realizan esos cálculos.

Instrucción de salto (ir a) y bucles

  • [30:07] La primera instrucción necesaria es un salto, a veces llamado ir a, seguido de una dirección de memoria.
  • [30:13] En lugar de pasar directamente a la siguiente instrucción en memoria, el programa salta a la dirección de memoria especificada y ejecuta la instrucción que hay allí.
  • [30:24] Esto permite al programa hacer un bucle; en el ejemplo del videojuego, a las instrucciones que añaden monedas al total del monedero y actualizan el mundo del juego y los gráficos les sigue un salto de vuelta al inicio, para que el juego pueda seguir ejecutándose indefinidamente.

Instrucciones de ramificación (condicionales)

  • [30:48] El otro tipo de instrucción crucial es la ramificación o condicional: si se cumple una condición dada, por ejemplo si dos números son iguales, entonces saltar a una dirección concreta.
  • [31:00] Una comparación puede implementarse con puertas lógicas, y añadir dicha lógica hace que un salto sea condicional, permitiendo ejecutar distintos conjuntos de instrucciones según los cálculos realizados hasta el momento o según entradas como un teclado o un ratón.
  • [31:17] Con los saltos condicionales el ordenador es completo de Turing: dado suficiente tiempo puede realizar cualquier cálculo.

Lenguajes de alto nivel, compiladores y funciones

Los lenguajes de alto nivel ocultan los detalles de bajo nivel

  • [31:41] Los programadores suelen utilizar lenguajes de programación de alto nivel, que ocultan los detalles de las instrucciones y las direcciones de memoria y facilitan el trabajo del programador.
  • [31:53] En C o C++, código como asignar Q a A si A es mayor que B, o de lo contrario a B, es legible para humanos y deja Q con el mayor de A y B.

Los compiladores traducen el código en instrucciones

  • [32:18] Un compilador toma este código y lo organiza en el conjunto correcto de instrucciones, decidiendo dónde se almacenan las variables en memoria, a dónde saltar y si usar números de 16 o 32 bits.
  • [32:30] Este proceso se denomina compilar el código.

Funciones y métodos como código reutilizable

  • [32:39] La idea de función o método es una de las simplificaciones más importantes para los programadores; la raíz cuadrada es un ejemplo matemático, pero las funciones también pueden ser arbitrarias, como para obtener correos electrónicos.
  • [32:55] Las instrucciones de una función usada repetidamente, como la raíz cuadrada, solo necesitan almacenarse una vez en memoria; cuando se llama, el ordenador salta a la ubicación de la función, ejecuta las instrucciones y vuelve con el resultado.
  • [33:16] Las funciones y métodos pueden compilarse en bibliotecas para que programadores de distintas épocas y lugares compartan código útil, como con los archivos DLL en Windows.

Saltos y bucles en los programas

  • [33:36] Los ordenadores tienen una instrucción para saltar a una dirección de memoria y ejecutar la instrucción que allí se encuentre, lo que permite bucles dentro de los programas.
  • [33:45] Algunos saltos solo ocurren cuando se cumple una condición.

Cómo los ordenadores controlan las pantallas con LED y bytes

Universalidad computacional de las máquinas de saltos

  • [33:47] Cualquier ordenador capaz de tales saltos puede realizar cualquier cálculo, siempre que tenga suficiente memoria y tiempo.

Brillo de LED controlado por voltaje

  • [34:10] Las bombillas son demasiado grandes para las pantallas, pero los diodos emisores de luz o LED son más pequeños y eficientes.
  • [34:18] Cuanto mayor es el voltaje a través de un LED, más brillante es.
  • [34:20] Una pantalla cambia electrónicamente el voltaje a través de cada uno de sus LED, y por tanto su brillo, según los datos del ordenador.

Escala de brillo basada en bytes

  • [34:30] Como los ordenadores manejan números en bytes, grupos de 8 bits, el brillo se escala de forma sensata de 0 a 255, el mayor valor que puede tomar un byte.

LED rojos, verdes y azules

  • [34:42] El ojo humano tiene células sensibles a la luz roja, verde y azul.
  • [34:46] Usar un conjunto de tres LED, rojo, verde y azul, y variar el brillo relativo de cada uno permite producir color.

Cómo los ordenadores renderizan píxeles, gráficos y sonido

Mezcla de colores de píxeles y tamaño de la memoria de visualización

  • [34:51] El ojo humano puede ser engañado para percibir todo el espectro de luz mezclando colores: rojo y verde dan amarillos y marrones, rojo y azul dan rosas, y los tres a plena intensidad dan blanco mientras que a intensidad parcial dan gris.
  • [35:07] Un pequeño punto compuesto por tres colores, independientemente de la tecnología utilizada, se llama píxel, y una pantalla organiza los píxeles en filas y columnas para formar una cuadrícula bidimensional.
  • [35:19] El vídeo de ejemplo a resolución máxima es de 1920 píxeles de ancho por 1080 píxeles de alto, y llenar una pantalla en memoria ocupa 3 veces el ancho por la altura en bytes.
  • [35:34] En términos más simples, el ordenador debe actualizar esta cantidad de bytes en memoria 30 o 60 veces por segundo y enviar el resultado a la pantalla.

Coordenadas de píxeles asignadas a direcciones de memoria

  • [35:49] Aunque mostrar gráficos pueda parecer puramente artístico, para un ordenador no es más que la lógica de puertas e instrucciones vistas hasta ahora.
  • [36:00] Cada píxel tiene una coordenada x y una coordenada y que corresponden a su posición en memoria.
  • [36:08] En una pantalla de exactamente mil píxeles de ancho, avanzar tres mil bytes desde el píxel superior izquierdo sale del final de la fila superior y pasa al píxel izquierdo de la segunda fila.

Dibujo de elementos del escritorio con bucles y aritmética

  • [36:25] Muchos algoritmos o largas listas de instrucciones dibujan ventanas, botones, texto y gráficos por computadora mediante aritmética y manipulación de bytes en memoria.
  • [36:37] Un bucle llena cada píxel con el color de fondo copiando repetidamente la secuencia de tres bytes que define el color, la barra de tareas se dibuja recorriendo filas con coordenadas y específicas, y un botón de inicio es un rectángulo de coordenadas x e y relleno con otro color.
  • [36:59] El texto se añade encima copiando patrones de píxeles predeterminados para cada letra o mediante algún otro algoritmo.
  • [37:06] Mostrar una ventana requiere su ancho, alto y la posición de su píxel superior izquierdo; sumar el valor x izquierdo y el ancho da el píxel del borde derecho, y si el usuario mueve o redimensiona la ventana toda esta aritmética se rehace y la ventana se redibuja.

Líneas, triángulos y formas 3D a partir de instrucciones simples

  • [37:29] El gráfico por computadora más simple es una línea entre dos puntos con sus propias coordenadas (x,y), y el algoritmo de Bresenham itera para dibujar dicha línea siguiendo una curva recta x-y familiar de las matemáticas escolares.
  • [37:44] Tres líneas forman un triángulo, que puede rellenarse con texturas, iluminarse con fuentes de luz simuladas y combinarse con miles de otros para formar una figura 3D.
  • [37:53] No importa cuán complicado se vuelva, todo se reduce a instrucciones de suma, multiplicación y salto compiladas en funciones.

El sonido como ondas de presión de los altavoces

  • [38:00] El sonido es la otra forma principal de salida de un ordenador, consistente en ondas de alta y baja presión que se desplazan por el aire y que producen los altavoces y auriculares.

Funcionamiento de altavoces y micrófonos

Mecanismo de altavoz mediante bobina e imán

  • [38:09] El sonido se produce al mover una membrana hacia adelante y hacia atrás.
  • [38:11] Un imán permanente unido a la membrana está situado dentro de una bobina conductora fija.
  • [38:15] Una corriente oscilante a través de la bobina atrae y empuja el imán, haciendo que la membrana oscile y genere sonido.

Generación de sonido digital a analógico

  • [38:20] El ordenador divide el tiempo en pasos cortos y especifica la corriente en cada paso enviando un número binario a una tarjeta de sonido.
  • [38:29] La electrónica convierte los valores binarios digitales en la corriente adecuada.

Micrófono como proceso inverso

  • [38:33] Un micrófono funciona exactamente de la manera opuesta.

Cómo procesan los ordenadores la entrada de teclado y ratón

Mensajes de entrada en memoria

  • [38:41] El manejo de entradas de un ordenador suele ser el mismo: las entradas dejan mensajes en memoria, que son grupos de bytes de longitud preestablecida que identifican el dispositivo y el contenido de la entrada.
  • [38:53] Una cola de mensajes puede contener tres mensajes de ocho bytes cada uno, que se decodifican como una pulsación de tecla, un movimiento del ratón de 30 píxeles a la derecha y la liberación de la tecla Mayús.

Matriz de teclado y mensajes de teclas

  • [39:10] Las teclas están dispuestas en una cuadrícula, y al pulsar una tecla se establece un contacto eléctrico entre una fila horizontal y una vertical, identificando la tecla precisa.
  • [39:19] Entre el teclado y la placa base, el mensaje que anuncia la pulsación o liberación de una tecla se transmite a la memoria del ordenador para que este pueda actuar en consecuencia.

Saltos condicionales para acciones del juego

  • [39:29] En un ejemplo de videojuego, el botón 'B' compra y el botón 'S' vende, lo que corresponde en Windows a los números decimales 66 y 83.
  • [39:42] El juego utiliza saltos condicionales basados en la última pulsación de tecla: un valor de 66 salta a las instrucciones de compra y 83 salta a las instrucciones de venta.

Seguimiento del ratón y detección de pulsación de botones

  • [39:56] Un ratón rastrea el movimiento izquierda-derecha y arriba-abajo sobre una superficie plana y qué botones están pulsados.
  • [40:05] Normalmente, el sistema operativo rastrea las coordenadas x e y en píxeles del ratón sumando o restando los cambios de posición recibidos del ratón.
  • [40:17] Cuando se pulsa el botón izquierdo en una ventana activa, el programa comprueba si la coordenada x del cursor está entre los lados izquierdo y derecho del botón, luego si la y está verticalmente dentro de él; si ambas son verdaderas, se considera que el botón está pulsado.
  • [40:43] Con 10 botones en pantalla, el programa comprueba cada botón por turno para ver si se ha pulsado.

De píxeles y sonido a la informática por capas

Cómo se representan las pantallas y el sonido en la memoria

  • [40:53] Una pantalla de computadora es una cuadrícula de píxeles, cada uno formado por una luz roja, una verde y una azul cuya luminosidad se establece mediante un byte correspondiente en la memoria de la computadora.
  • [41:05] Por lo tanto, un píxel tiene un color arbitrario, y un grupo de píxeles juntos forma una imagen.
  • [41:10] El sonido se registra midiendo el movimiento de las ondas sonoras y guardándolas como números binarios en la memoria, con el proceso inverso utilizado para la reproducción.

Las entradas y la abstracción por capas de la computación

  • [41:18] Los dispositivos externos envían mensajes a la computadora que se colocan en la memoria, permitiéndole identificar entradas como una pulsación de tecla o el movimiento del ratón y luego actuar sobre ellas.
  • [41:31] Al orador le parece asombroso que dopar el silicio con elementos impuros y realizar operaciones lógicas relativamente simples permita a las personas ver y crear videos, procesar información e incluso habitar mundos virtuales.
  • [41:44] La computación construye conceptos más simples a partir de otros más complicados: los pares CMOS forman una puerta NAND, las puertas NAND forman cualquier puerta lógica, las puertas lógicas forman instrucciones, las instrucciones convierten los algoritmos en funciones, y las funciones construyen programas de cualquier complejidad.

Las computadoras como ejecutoras rígidas y poco intuitivas

  • [42:03] Esto también significa que las computadoras son muy tontas: no tienen intuición y deben seguir rígidamente programas en los que cada posible eventualidad se detalla con gran precisión.

Lee los subtítulos disponibles con marcas de tiempo o transcribe podcasts, clases y audio o vídeo local. Extractor gratuito de subtítulos de YouTube.

[0:00] [Music] In this video I will try to give a broad overview of how a computer works from the ground up. Subtitles are available. It will get a little bit technical, but I will try to keep things as simple as possible. There will be a summary at the end of every section and links to further explanations in the description. Hopefully this overview will teach you something new or give you a new perspective on things.

[0:32] Probably nobody in the world knows every single nuance of how a computer is built and operates. This is why when you hear this sound [Beethoven's 5th symphony] that is a warning that I am making massive oversimplifications which I'm sure you'll point out to me in the comments. [Beethoven's 5th symphony] That was the warning for the entire video. [Music] Modern computers at their core are electrical circuits.

[1:04] A very simple circuit might consist of a battery connected to a switch, then a light bulb, then back to the negative terminal of the battery. Modern computer components typically supply a voltage of 3.3 or 5 volts between the positive terminal and the ground or negative terminal if you like to think of it that way. Computers treat information as binary: on or off, true or false, one or zero, based on if the voltage is high or low. The important component in our circuit here is the push switch which. comes in two flavors.

[1:37] push to make, that's when a person presses down, and the circuit is completed between the two terminals, and the bulb lights up. The push to break switch is exactly the opposite. This is the symbol for a transistor: more specifically, it's a Metal Oxide Semiconductor Field Effect Transistor or MOSFET. Its source and drain are like the two terminals of a switch, but it has a third terminal called a gate. just like switches, there are two types: the N-channel type makes a circuit when a high voltage is applied to the gate, like a push to make. The P-channel breaks the circuit when a high voltage is applied, like a push to break.

[2:19] So, transistors act like switches, except instead of a person pressing it down a voltage is applied. In modern computers, these types of transistors are used in pairs, referred to as CMOS or Complementary Metal Oxide Semiconductor. The gate terminals of a given pair are always connected together, so they receive the same input. Here is a simple example: if we apply a high voltage or 1 to the input, the N-channel MOSFET opens a route between high voltage and the output. The P-channel closes the root to ground.

[2:52] If we apply a low voltage or 0 at the input, the P-channel opens a path to ground. OK, so this circuit seems pointless, we got the same thing at the output as we did at the input, but let's swap around the two MOSFETs. Now, when we apply a high voltage or 1 to the input the N-type opens a route to low voltage or 0. When we apply a 0 to the input we get a 1 at the output. Whatever we put in at the input, we get the opposite at the output. Later we will come back to how this forms the basis of all modern processors. Understand that it is vast networks of CMOS pairs like these which allow computers to think.

[3:33] [Beethoven's 5th symphony] For now, let's see how transistor networks are made in basic terms. Silicon is a semiconductor with four valence electrons which is doped, or mixed with, other elements. Gallium, for example, has three valence electrons - one less than silicon, hence more positive or P-type. Meanwhile, an element like arsenic has five valence electrons - one more than silicon, therefore adding a negative charge, hence N-type.

[4:03] Trace amounts of these elements typically one for every million silicon atoms or so are implanted by chemical diffusion or by firing them out of a particle accelerator. Transistors are made by sandwiching a region of one of the dopants between two of the other. Let's look more closely at the N-channel configuration. This by itself does not conduct electricity, but when an electric field is applied to it a conducting channel forms, hence the name: Field Effect Transistor. This can be thought of in simple terms as the electric field attracting electrons from the N-doped region, which has a surplus, to the P-doped region, which has a deficit.

[4:40] Near the semiconductor stack we have a conducting electrical terminal. When it's at high voltage, an electric field forms and the transistor conducts, but to stop a short circuit. we need to add an insulating layer. between them. The contact is metal, the insulator is silicon oxide. and finally we have the doped semiconductor, hence the term MOSFET. For a computer we need millions of interconnected CMOS pairs and they must be small and close together so that electrical signals can travel between them quickly.

[5:13] Making a processor typically begins with a solid block of P-doped silicon called a die. Transistors are then created on top of the die by a process called lithography: "writing on stone". There are two main techniques used in lithography. The first is deposition: chemically building up a layer of controlled, predetermined thickness across the entire die. This means that, for example N-doped silicon can be coated all over the top of the P-doped die. Unwanted surface material is then removed by a second technique called etching. This is done by applying chemicals or hot plasma to the top of the die. several steps are taken to ensure that the etching is targeted at specific areas and therefore material is removed selectively.

[6:02] A chemical termed a photoresist is deposited onto the die. light is shined through a mask exposing predetermined areas of the photoresist. The exposed areas must be the same size or larger than the wavelength of light used, hence very short wavelength ultraviolet light is used for the lithography. A special etching method is used to remove only regions of photoresist which were exposed and nothing else. This opens up gaps in the photoresist and then another etching method is used which targets everything except the unexposed photoresist.

[6:39] Finally, the remaining photoresist is etched away. As a result, material has been removed wherever there are any gaps in the mask. The two techniques of deposition and etching used in conjunction mean that the N-type dopants for all the transistors on the die can be added simultaneously. Next, the silicon oxide is deposited and etched and finally metal is deposited and etched away to leave metal channels on top of the die. These metal features form not just the conducting terminals of the transistors, but also the tracks equivalent to wires in a circuit which connect the transistors as required.

[7:16] Every time, photoresist is deposited, exposed through a mask, gaps are made and a die is etched. Finally, the billions of transistors are assembled and connected together by this method. There may be three CNOS pairs with three different inputs, then going out to four different CMOS pairs somewhere else and so on and so on. [Beethoven's 5th symphony] To summarize: computers handle information as ones and zeros, when voltage in an electrical circuit is either high or low.

[7:48] Transistors act as electronic switches, changing between these two states. The transistors always come in complementary pairs, so when one half of the pair opens, the other closes. Lithography is the process by which huge numbers of interconnected transistors are built up on a block of silicon. [Music] To understand why transistor networks are useful, we need to talk about a branch of mathematical logic called Boolean algebra.

[8:18] Rather than go into the full gory mathematical details, I will just illustrate the basic concepts with some not too serious examples. Let's say some friends are choosing a restaurant. Alice is happy when the restaurant serves burgers. Bob is happy when the restaurant does not serve burgers. We can think of evaluating restaurants in this case as something called a gate: an object which takes a binary input true or false, 1 or 0 and returns a binary output. In this case, the input is whether the restaurant has burgers and the output is if someone is happy with the restaurant.

[8:54] For Alice the gate is simple: the output is the same as the input. In electronic terms the circuit is just a connection. For Bob the gate is what's unimaginably called a NOT gate. This is a symbol typically used to denote it. In the previous section we have seen how this CMOS pair acts as a NOT gate. Let's consider a more interesting example, when the logic gates can have multiple inputs. Such gates have pretty straightforward names as we'll see. Now the friends are choosing restaurants which might serve pizza, noodles, both or neither. Alice is happy when the restaurant serves at least one of the two options or both. This idea is represented by what is called an OR gate. This is the symbol.

[9:35] Bob wants choice, so he wants both pizza and noodles on the menu, hence the AND gate. Charlie likes it if the restaurant serves pizza or noodles but not both: let's say she thinks that they wouldn't do a good job if they weren't specialized enough. The corresponding gate is called exclusive or XOR for short. Each of these gates also has a complementary gate: basically the same gate with a NOT gate after it. For example the NAND gate gives a 0 when all its inputs are 1, and gives a 1 otherwise.

[10:08] These complementary gates are denoted by the usual symbol with a circle at the output. For a computer, these and all other possible gates must be implemented through CMOS pairs. Connecting two pairs as follows creates a NAND gate. The N-channel and P-channel transistors still work in pairs. Only when a high voltage or 1 is applied to both pairs of inputs do the paths to high voltage close. and the path to ground opens so. a 0 is output. This is exactly the behavior of a NAND gate.

[10:40] The NAND gate is important because it's what's called universal: this means that any other gate can be created out of NAND gates as long as there are enough of them. Now, there are more efficient ways to make certain gates, but in essence this means that the problem of implementing logic gates through CMOS pairs is solved. There are also gates with three, four, or as many inputs as necessary. For example, take two AND gates connected as shown here, and they simply become a three input AND gate and so on and so forth. [Beethoven's 5th symphony] To summarize: logic gates are conceptual, mathematical objects which allow us to make deductions based on binary true or false statements.

[11:18] For example if it's true that today is Saturday or today is Sunday, then it's also true that today is the weekend. We have now seen how the CMOS pairs from the last section can be used to practically implement these gates in terms of electronic binary logic. [Music] Now we shall see how computers handle numbers and use logic gate networks to do arithmetic. We are all used to base 10 numbers meaning that there are 10 digits from 0 to 9.

[11:51] The digits represent multiples of powers of 10 which are 1, 10, 100, 1000, and so on. Modern computers use base 2 numbers with just 2 digits: 0 and 1. Binary digits are multiples of powers of 2 which are: 1, 2, 4, 8 and so on. For example, in base 10 the number 953 is 9 times 100 plus 5 times 10 plus 3 times 1. In binary, the number 1 0 1 is 1 times 4 plus 0 times 2 plus 1 times 1 which is 5 in base 10.

[12:25] Any number in base 10 can be represented by a number in base 2 and vice versa. To represent the number 1 0 1 3 electrical tracks in order would have their voltage on off on. Each of these tracks carries a binary digit or bit. With three electrical tracks this is called a 3-bit number. There are similarly 4-bit numbers 8-bit numbers and so on. Of course the 4-bit number 0 1 0 1 is equivalent to the 3-bit number 1 0 1.

[12:56] Let's consider adding together a pair of 1-bit numbers A and B to get C. 0 + 0 = 0 0 + 1 = 1. What happens when we try to add 1 + 1 in binary? The same thing as happens when we add 5 + 5 in regular base 10. There is no digit big enough, so we put a 0 in that column and carry the 1 to the next column. so to guarantee being able to store the result for any possible values of A and B the result C must be a 2-bit number. The bit on the right is 1 when A or B is 1, but not both: this is the behavior of the XOR gate if you recall. Charlie from the last section.

[13:35] The bit on the left is 1 only if A and B are 1, ergo the AND gate. Therefore C is obtained by connecting A and B to gates like this. When adding numbers A and B larger than 1-bit, things get more complicated with three input gates because there is now a bit from A, a bit from B and a carried bit. As I said in the previous section: NAND gates are universal, meaning any required gate network can be implemented using enough of them.

[14:17] [Beethoven's 5th symphony] In base 10, multiplying by 10 is easy: just add a 0 onto the end of your number. In base 2, the same is true for multiplying by 10 in binary or 2 in base 10. So, multiplying by the numbers 10, 100, 1000 in binary just involves shifting each bit to the left and putting a 0 on the end, which is unimaginably called a bit shift. What about multiplying by an arbitrary number, say for example 11 in binary?

[14:48] This is the same as multiplying by 10 multiplying by 1 and adding the two together. So, binary multiplication of A by an arbitrary number B works as follows: begin with zero. If the rightmost bit of B is 1, add A. Bit shift A once and if the next bit of B is 1, add this to the total. Continue for every bit of B. Computers also rely on making comparisons of numbers, such as: Is A equal to B? Is A greater than B?

[15:18] And so on. The computer might have the current time in seconds stored as a binary number A updated every second and the time to set up an alarm stored as B. The alarm would be made to go off when A is equal to B. To do this, the computer must check that every bit of the number A is the same as the corresponding bit of B. So, the XOR gate returns 1 when an input is 1 and the other input is 0, in other words when its inputs are different. The XNOR gate which is the complement of the XOR meaning it returns the opposite to the XOR therefore returns a 1 when its inputs are the same. A bunch of XNOR gates applied to each pair of bits of A and B return whether those bits are equal or not.

[15:57] The and gate returns a 1 when all its inputs are 1. So applying it to the XNOR gates returns a single bit which is 1 if and only if A is equal to B. There are also ways to implement subtraction, division and other comparisons all using gate networks. For example bit shifting the other way divides a number by two. These are all implemented using transistors etched on a chip. Just a note: when I say the word number in this video I am referring to an integer or whole number. There. is also a way to store fractions in a binary version of scientific notation called floating point numbers or floats.

[16:32] I won't go into how they work but the general principle outlined here still applies. To summarize: a sequence of binary on off electrical signals is used by computers to represent a number in base 2 as opposed to base 10 which is used by people day to day. Networks of logic gates can be used to add, subtract and compare binary numbers, and with a few extra steps multiply and divide them too. [Music] We have seen how circuits composed of transistors can be used to implement addition and other algebra for any number with arbitrary binary digits or bits.

[17:09] If you want to build a computer, we would have to choose exactly how many electrical tracks and gates to have available for representing a number. This is like when you're filling in a form, and it has a set number of boxes physically printed on it for putting in your age. For commercial computers this is always a multiple of 8. 8 bits are called a byte. The computer will have adder circuits and so on with the types I described in the last section which take 1 byte or 8-bit numbers, 2 byte or 16-bit numbers, 4 byte or 32-bit numbers as inputs.

[17:40] No matter of how many bytes a number is comprised, one of its bits can be set aside to denote a plus or minus sign. When a number is signed in this way, if the leading bit is 0 then, the number is positive. If the leading bit is 1 then, the number is negative. As anyone who has ever taken a mathematics exam knows: it's important to store your workings. Whichever operation a computer undertakes, the inputs and outputs must be somehow stored. To do this, a type of circuit called a latch is used.

[18:10] Once it has latched, it will stay that way for a long time and can therefore be used to store a bit of data. 8 latches store a byte and so on. This is an example of what's called a D-latch comprised of NAND gates. You may notice that this looks rather strange: before we've seen gates in a strictly sequential manner where the output of one gate goes directly to another. Now there is an output from one going to the input of another, but then the output comes right back. It is this kind of interconnection that allows this network of gates to hold and retain its output value 0 or 1.

[18:44] Nothing will change unless the E or enable input is 1. When enable is 1, whatever bit is applied to D will propagate to the output. The computer will carry out an operation, addition for example, enable a bunch of latch circuits to store the output and then switch the enable back off. The result will then be held there as long as is required. 8 of these latches can form register which will store a byte of data as long as it's required. An add circuit of the type we looked at in the previous section would have such registers to store the inputs before the addition takes place and a register to capture the result of the addition.

[19:23] It takes some small but significant amount of time for electrical signals to propagate, for transistors to finish switching and so on. To guarantee that the operation is fully carried out before attempting to read out the answer, all computers have a clock. In basic terms an oscillating crystal switches the voltage on and off, on and off, at a very specific rate. At the time when this video was made computer processors have typical clock speeds of 2 Gigahertz, meaning that the clock switches at 2 billion times a second.

[19:55] The regular switching allows events to be synchronized. To fully carry out an addition operation it will take at least 3 clock cycles. On the first clock cycle numbers would be loaded into the input registers, then the addition circuit can work over the next clock cycle. Finally on the third clock cycle, the output register gets an enable signal and stores the result. Actually, most operations take much。 longer than one or even, three clock cycles to carry out. We have seen in the previous section that, multiplication takes several adding, steps to accomplish.

[20:30] Nonetheless, whether it takes one or a hundred cycles the clock is still used。 to synchronize when an operation begins until the output is ready. All the so-called arithmetic logic, that is: all the arrays of logic gates which do addition and subtraction is physically located together with the registers on a chip called the processor or Central Processing Unit. There are also circuits in there called the cache, which nowadays can store tens of kilobytes of data as the intermediate stages of calculations for example.

[21:01] There is a need for a larger and longer term way to store many more bytes of data than the registers and the cache. Computers have separate physical chips of random access memory or RAM which makes use of capacitors to store this data. If a capacitor is charged, it has a high voltage and therefore a value of 1. If it's discharged, it has 0 volts relative to ground and so is 0. The charge leaks or is lost over time, but is topped up by the memory circuits as long as the computer is powered.

[21:31] A typical laptop computer has tens of gigabytes or billions of bytes of RAM. Every byte stored in RAM has its own address like a post box in an apartment block. The address is itself a binary number. The RAM has many transistors forming gate networks which ensure that when it receives the address in binary format from the processor, it then returns the byte stored at that address. Until recently, computers wouldn't usually have more than 4 gigabytes of RAM. Each of those bytes requires a unique address, so memory addresses were 32-bit numbers. Such 32-bit numbers go up to just over 4 billion, so that used to be fine.

[22:10] When RAM got bigger there effectively weren't enough addresses, so now 64-bit numbers are used for memory addresses. This is the difference between 32 and 64-bit programs. So, let's say you're playing a video game where you have a number of coins in your wallet. The video game will keep track of the address where the wallet total is stored. If you found eight more coins, the game will fetch the number currently in your wallet from that address, load it into the register, load a biary number corresponding to 8 in base 10. into the other register, add them together and put the results. back into the address with the wallet total.

[22:47] We will look at this in more. detail in the next section. Computers also store huge volumes of. data on hard disk for decades at a time. even without power. A hard disk is covered in tiny magnetic domains which can point up. or down corresponding to 1 or 0. As the disk spins, a sensor head can. either passively read off the orientation of the magnets as bits, or actively flip the orientation of the magnetic domains to write data onto the disk. Each of the bytes also has its own. separate address.

[23:19] A laptop or personal computer can store hundreds of gigabytes on a hard disk. there are other technologies like flash memory, DVDs and so on that I won't go. into here. The fundamental limit on how fast a computer can do operations is the speed. of light, which can go about 15 centimeters or. half a foot. during a typical computer clock cycle. so it would take multiple cycles for a computer. larger than that to fetch any data. Realistically, transistors switch much. slower than that, while a hard disk takes time to spin up. and scan. to read the data. In terms of types of computer memory: the cache is small, but quick to access; the RAM stores many more bytes of data, but takes, longer to read; the hard disk takes the longest to read, but stores a lot of data. almost permanently; so, there is a trade-off between how quickly the data. can be retrieved. and how much can be stored. From now on in this video, I will explain things as. if the computer just has a single pool. of memory which it can instantly read. In reality things are more complicated,

[24:20] as I've just described. [Beethoven's 5th symphony]. To summarize: computers have a clock. which synchronizes the operations being. performed and. ensures that there is enough time to. finish performing one operation before. starting another. Computers process binary numbers in. groups of 8 bits called a byte. Registers are used to. store numbers during computations. and at other times numbers are stored in. the cache, in random access memory. and on a hard disk. Each byte in memory has its own unique address which is itself a binary number.

[24:56] [Music] We have a way of implementing binary operations and storing the results, but the computer needs a way to determine which operation to use and when. This is called an instruction. There are instructions such as: add two numbers, and copy this number. Computers use what's known as the von Neumann architecture, which means that the instructions are stored in memory as binary numbers amongst other data. For example, the instruction number 16 and base 10 or this byte in binary might mean: add together two 8-bit numbers and store the result.

[25:34] Instruction number 17 might mean the same thing but for 16-bit numbers and so on. When the computer encounters an instruction, it will use a comparison circuit which we looked at in a previous section to switch on the logic circuit for the necessary operation. If the byte is equal to 16, switch on the add circuit. How does the computer know when a byte is an instruction or not? 16 might be the instruction to add, or it might be the number of coins in a video game. Well, everything has to do with a precise order in which the bytes appear in memory. First comes the instruction byte.

[26:08] If the instruction is to add, the computer will need the two memory addresses of the things being added and the memory address where the result is to be stored. Remember that memory is like post boxes, for a big apartment building with a, unique address on each byte. In the case of modern 64-bit systems addresses are 8 bytes long. Therefore, the entire add instruction has one instruction byte and 24 bytes of addresses; 25 in total. On the other hand, if the instruction is to copy a number, it just needs to be followed by the origin and destination addresses, meaning the whole thing takes 17 bytes in total.

[26:45] The trick is that each type of instruction always takes up a set number of bytes and - crucially - the next instruction immediately follows on after the previous one. So, when the computer encounters the add instruction not only does it carry it out, but it knows that the next instruction is precisely 25 bytes along. To start with, the computer interprets byte number 0 - the one at the very start of memory - as an instruction and thereafter goes from instruction to instruction. Conversely, if there has been an error and the next instruction is not where it's supposed to be - tough luck! The computer will probably crash. How does the computer actually carry out an add instruction?

[27:22] The number from the first address is loaded into one input register and the second address into another input register. The add circuit is enabled and it does the addition. Then, after a sufficient number of clock cycles, the result can be written from the output register to the required address in memory. What happens if the instruction is to add two 16-bit numbers together? The computer simply goes to the address of number A and instead of getting just one byte, it gets that byte and then one immediately after. The same for number B. and the result C. [Beethoven's 5th symphony] A computer program is a collection of instructions (and addresses) to be done in order. The computer goes from instruction to instruction to make the program run. Let's look at a specific example: part of the game, which is just a program after all, where the player has a wallet with coins in.

[28:10] This is what the contents of memory might look like. Byte number 0 is the instruction to add. Then come two addresses: the address of the wallet total and the number of coins the player has just found. The third address is the wallet again. after the addition the wallet total will be overwritten. No matter what, the computer will now interpret byte number 25 in memory as an instruction. It is another add instruction. The addresses of the wallet and the amount of coins the player has made from selling items are the inputs.

[28:40] The wallet address is the output again. The next instruction is 25 bytes further along at byte 49. The program keeps going on with millions of other instructions required to make the game function. In this case, the wallet total is being used a lot, so it will probably be held long term in the processor's cache as well as the RAM. When the player saves the game it will be written to a save file on the computer's hard disk. To summarize: the computer interprets certain bytes in memory as instructions for which operation to carry out.

[29:15] Computer programs are stored in memory. They are just large sequences of instructions, memory addresses and numbers. The computer goes from instruction to instruction like clockwork, always knowing based on the type of the current instruction how far along the next one is. [Music] So far, we've looked at instructions which work in a linear manner: copy a number, add two together and so on. The program would always produce the same result and eventually it would just get to the end of memory and stop.

[29:48] We need a few more instructions to make a computer what's known as Turing complete. Being Turing complete means that it can eventually carry out any possible computation: load a web page, render video game and so on. The only difference between two Turing complete computers is how fast they are at doing those computations. The first type of instruction a computer needs is what's called a jump or sometimes called a go to. Following the instruction byte is a memory address. As the name suggests, instead of going directly to the next instruction in memory, the program jumps to the specified memory address and carries out the instruction there.

[30:24] This means that the program can now do a loop. In our video game example, we have seen how instructions are used to add numbers of coins to a total kept in a wallet. These instructions and all the others required to update the game world, render the graphics and so on are followed by a jump instruction back to the start. This way the game can keep running indefinitely. The other crucial type of instruction that a computer needs is a branching or conditional instruction. If a given condition is met, for example if two numbers are equal, then jump to a particular address.

[31:00] We have already seen how a comparison can be implemented with logic gates. Adding such logic makes a jump conditional, allowing different sets of instructions to be executed based on calculations performed so far, or inputs to the computer such as a keyboard or mouse. With conditional jumps the computer is Turing complete: given enough time it can do any calculation. At this point it's worth mentioning how a real program might actually be written. If you thought that things were quite confusing so far, you're not wrong. Remembering which instruction does what, which memory addresses have what data stored in them, where jumps go and so on.

[31:38] This is all hard to keep track of. Programmers typically work with what are referred to as high level programming languages. This means that all the nuts and bolts of instructions and memory addresses are hidden away and instead life is made easier for the programmer. For example this is a bit of code in the C or C++ language. This code is readable by humans. If A is greater than B, set Q to be A; otherwise, when B is greater or equal to A, set Q to be B. In other words, the number Q will end up with whichever number is larger out of A or B.

[32:14] This is easy to understand for the programmer and anyone who tries to read it. A program called a compiler will take this code and arrange it into the correct set of instructions, sort out where the variables are stored in memory, where to jump, do we need to use 16-bit or 32-bit numbers and so on. This is what's referred to as compiling the code. There are many aspects of programming languages which simplify the job of the programmer, but one of the most important is the idea of a function or method. In mathematics, the square root is a function which takes a number and returns another. Certainly there are implementations of the square root function in computer code, but there are also more arbitrary functions and methods such as for fetching emails and so on.

[32:55] Say that a program needs to evaluate the square root of different numbers repeatedly. The instructions which comprise the square root function need only be stored in memory once. Whenever the function needs to be used, or called, the computer will jump to the function's location in memory, carry out the instructions and jump back with the result to the place in the program where it left off. Functions and methods can be compiled into libraries so that programmers across time and space can share useful code that they've written. If you've ever seen a DLL file on Windows, that's what that is. Once a function or method has been written efficiently, other programmers can use it without needing to spend much time on it.

[33:34] [Beethoven's 5th symphony] To summarize: computers have an instruction to jump to a memory address and carry out whatever instruction is there. This allows loops within programs. Some jumps only happen when a condition is met. any computer that is capable of such jumps can carry out any computation as long as it has enough memory and time to do so. [Music] Chances are, you're watching this video, on some sort of display. There are many technologies past and present which have been used for computer monitors, so I will speak in generalities.

[34:10] Light bulbs like at the start of the video are too large, but light emitting diodes or LEDs are smaller and more efficient. The higher the voltage across an LED, the brighter it is. A display is capable of electronically changing the voltage across each of its LEDs and therefore their brightness according to data from the computer. Since computers handle numbers in bytes, in other words groups of 8 bits, it makes sense to have the brightness go up on a scale from 0 to 255 - the largest value a byte can take.

[34:42] The human eye has cells sensitive to red green、 and blue light. By using a set of three LEDs: red, green and blue, varying the relative brightness of each one, the human eye can be tricked into perceiving the full spectrum of light. A mix of red and green gives yellows and browns. Red and blue gives pinks. All three colors at full brightness give white and at partial brightness give grey and so on. A little spot composed of three colors like this, no matter what technology is used, is called a pixel.

[35:14] A display has pixels arranged in rows and columns to form a 2-dimensional grid. For example, this video at maximum resolution is 1920 pixels in width by 1080 pixels in height. The number of bytes it takes to fill a display in memory is 3 times the width times the height. In simplest terms, the computer must update this many bytes in memory 30 or 60 times per second and send the result to the display. So, for example, if you full screen this video in its maximum resolution, each frame would take up this many bytes in memory.

[35:49] While displaying graphics and images may seem like a purely artistic undertaking, and in some sense it is, in actual fact for a computer it is nothing more than gate logic and instructions we have seen so far. Each pixel has a horizontal or x coordinate and a vertical or y coordinate which corresponds to its position in memory. For example, let's say your display is exactly a thousand pixels wide and you start with the top left pixel, if you move forward three thousand bytes in memory or the equivalent of a thousand pixels, you'll go off the end of the top row and onto the left pixel of the second row.

[36:25] There are many algorithms or long lists of instructions to draw windows, buttons, text and computer graphics. all by using this kind of arithmetic and manipulating bytes in memory. To display a simple desktop environment, a loop fills every pixel with the background color by repeatedly copying the sequence of three bytes that uniquely defines the color. The taskbar is drawn by looping over only rows of pixels with specific y coordinates. A start button is created by filling a rectangle with a given range of x and y coordinates with another color.

[36:59] Text is added on top by copying pre-determined patterns of pixels for each letter or through some other algorithm. To display a window, it's necessary to know its specific width and height and the current position of its top left pixel. Adding the x value of the left pixel and the width by simple arithmetic gives the rightmost edge pixel. A title bar can then be drawn, along with a border text and so on. If the user moves or resizes the window, all of this arithmetic has to be redone and the window redrawn.

[37:29] The simplest computer graphic involves drawing a line between two points both with their own set of coordinates (x,y). The bresenham algorithm involves a loop which draws just such a line by following a straight x-y curve familiar from school mathematics. Draw three lines and you have a triangle which can be filled with textures, illuminated by simulated light sources and combined with thousands of others to make a 3D shape. No matter how complicated it all comes down to addition, multiplication and jump instructions compiled into functions.

[38:00] Sound is the other major form of output from a Computer. Sounds are waves of high and low pressure moving through the air. Speakers and headphones produce sounds by moving a membrane back and forth. There is a permanent magnet attached to the membrane inside a fixed conducting coil. An oscillating current through the coil pulls the magnet in and out, making the membrane oscillate and creating a sound. The computer breaks up time into short steps and specifies the current at every step in time by sending a binary number to a sound card. Electronics turn the digital binary values into the appropriate current.

[38:33] A microphone works in exactly the opposite way. There are many input devices out there, but the way a computer deals with inputs is usually the same. The inputs leave so-called messages in memory, which are groups of bytes of preset length, identifying the device and what exactly the input consists of. For example, a message queue may have it three messages of eight bytes each: when decoded, the first one, states that the a key has been pressed down; the second states that the mouse has moved 30 pixels to the right; and the third that the shift key has been released on a keyboard.

[39:10] The keys are arranged into a grid. When a key is pressed, it makes an electrical contact between a horizontal and vertical row, allowing the precise key to be identified. Between the keyboard and the computer's motherboard, the message announcing when a key is pressed down or released is relayed to computer memory, allowing the computer to act on it. In our video game example, imagine that the 'B' button is used to buy things and the 'S' button is used to sell. In Windows, these key presses have corresponding decimal numbers. 66 and 83 respectively. In terms of instructions, the game would have conditional jumps based on the value of the last keystroke.

[39:46] If the keystroke value is 66, then a computer would jump to a set of instructions corresponding to buy; if 83, it would jump to instructions corresponding to sell. A computer mouse tracks how far left or right and up or down it has moved along a flat surface and also which buttons have been pressed. A program, typically the computer's operating system, keeps track of the x and y pixel coordinates of the mouse by adding or subtracting any changes in position received from the mouse.

[40:17] Say that a window with a button is currently active when a user presses down the left mouse button, the program will check the x coordinate of the mouse cursor against the dimensions of the button. If x is greater or equal to the left side of the button and less than or equal to the right side of the button, then the click is horizontally inside the button, the programs then check the y-coordinate is vertically inside the button too. If both are true, the button is considered pressed. If at any moment you have 10 buttons on screen, the program will check every button in turn if it's been pressed down or not.

[40:51] [Beethoven's 5th symphony] To summarize: a computer display is a grid of pixels. Each one a group of a red, a green and a blue light. The brightness of each light is set by a corresponding byte in computer memory. A pixel therefore has an arbitrary color and a group of them together makes an image. Sound is recorded by measuring the motion of sound waves and saving them as binary numbers in memory. The reverse process is used to play back the sounds. External devices send messages to the computer, which are placed into memory, allowing the computer to identify inputs, such as when a key has been pressed or the mouse has been moved, and then act upon them.

[41:29] Finally, I want to take stock of the entire video. I think it's amazing how doping silicon with impurity elements and performing relatively simple logical operations allow us to watch and create videos process information, and even inhabit virtual worlds. Computing is all about building up simpler concepts to achieve more complicated ones. If you've got CMOS pairs, you can make a NAND gate; if, you've got NAND gates, you, can make any logic gate; if you have logic gates, you can make instructions; if you have instructions, you can make algorithms into functions; from functions you can build up programs as complicated as you like.

[42:03] This also means that computers are very dumb: they have no intuition and must rigidly follow programs which have every possible eventuality spelled out in great detail.

Abrir en el lector de Vidleaf

Busca citas exactas entre comillas, compara subtítulos bilingües y exporta TXT, SRT o Markdown con marcas de tiempo.

Atribución y licencia

«How a Computer Works - from silicon to apps» por Improbable Matter (https://www.youtube.com/@improbablematter), con licencia CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Vídeo original: https://www.youtube.com/watch?v=5f3NJnvnk7k. Esta página presenta una transcripción con marcas de tiempo; la persona o entidad creadora no está afiliada a Vidleaf ni lo avala.

¿Eres el autor o titular de derechos? Solicita correcciones o retirada en copyright@vidleaf.app.

Última actualización