<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>CPU on Jefferson Oliveira</title><link>https://jeffersonmourak.com/tags/cpu/</link><description>Recent content in CPU on Jefferson Oliveira</description><generator>Hugo -- gohugo.io</generator><language>en</language><copyright>All content provided by this website are my own opinons and beliefs and are distrubuted under the &lt;br/></copyright><lastBuildDate>Sun, 19 Jan 2025 08:27:04 -0300</lastBuildDate><atom:link href="https://jeffersonmourak.com/tags/cpu/index.xml" rel="self" type="application/rss+xml"/><item><title>Lembra de mim?</title><link>https://jeffersonmourak.com/blog/memory/</link><pubDate>Sun, 19 Jan 2025 08:27:04 -0300</pubDate><guid>https://jeffersonmourak.com/blog/memory/</guid><category domain="https://jeffersonmourak.com/tags/cpu/">CPU</category><category domain="https://jeffersonmourak.com/tags/memory/">Memory</category><category domain="https://jeffersonmourak.com/tags/combinational/">Combinational</category><category domain="https://jeffersonmourak.com/tags/sequential/">Sequential</category><description>&lt;blockquote>
&lt;p>Olá todo mundo, este é o terceiro artigo na série sobre computadores, e também o último com esse cabeçalho aqui, pois daqui para a frente é recomendado que você já tenha lido os dois artigos anteriores:&lt;/p>
&lt;ul>
&lt;li>&lt;a href="https://jeffersonmourak.com/blog/logic-gates/">Portas lógicas&lt;/a>.&lt;/li>
&lt;li>&lt;a href="https://jeffersonmourak.com/blog/the-binary/">Prazer, Binário.&lt;/a>.&lt;/li>
&lt;/ul>&lt;/blockquote>
&lt;p>Nos artigos anteriores, nós vimos como portas lógicas podem ser usadas para fazer comparações e também calcular operações aritméticas, porém ainda não vimos como o computador pode guardar uma informação ao longo do tempo.&lt;/p></description><content:encoded><![CDATA[<blockquote>
<p>Olá todo mundo, este é o terceiro artigo na série sobre computadores, e também o último com esse cabeçalho aqui, pois daqui para a frente é recomendado que você já tenha lido os dois artigos anteriores:</p>
<ul>
<li><a href="https://jeffersonmourak.com/blog/logic-gates/">Portas lógicas</a>.</li>
<li><a href="https://jeffersonmourak.com/blog/the-binary/">Prazer, Binário.</a>.</li>
</ul></blockquote>
<p>Nos artigos anteriores, nós vimos como portas lógicas podem ser usadas para fazer comparações e também calcular operações aritméticas, porém ainda não vimos como o computador pode guardar uma informação ao longo do tempo.</p>
<p>Outra coisa que também iremos fazer aqui é categorizar cada tipo de chip: os que foram mostrados anteriormente são <em><strong>combinacionais</strong></em>, o que significa que eles não precisam de nada além de sinais nas suas entradas para poder computar um resultado, mas existem também os <em><strong>sequenciais</strong></em>. A diferença entre eles é que o sequencial depende não só dos sinais das entradas, mas também do valor anteriormente processado.</p>
<p>Um jeito muito prático de usar portas lógicas para guardar informações é usando um chip chamado de <em><strong>flip-flop</strong></em>, que está representado abaixo. Ele contém 2 entradas: a de cima <code>set</code> e a de baixo <code>reset</code> (você pode clicar no circuito abaixo para interagir com eles).</p>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/memory/">view it on the blog</a>.</em></p>
<pre><code>╭───────╮     ╭───╮           ╭───╮     ╭───╮
│ reset ├○───▶┤NOT├○╮     ╭──▶┤   │ ╭──▶┤LED│
╰───────╯     ╰───╯ │     │   │AND├○●   ╰───╯
                    ╰─────┼──▶┤   │ │        
                          │   ╰───╯ │        
            ╭─────────────┼─────────╯        
╭─────╮     │ ╭─────────╮ │                  
│ set ├○╮   ╰▶┤         │ │                  
╰─────╯ │     │[or:_or_]├○╯                  
        ╰────▶┤         │                    
              ╰─────────╯                    </code></pre>
<p>Se parar para analisar, é bem simples: seguindo a trilha do <code>set</code>, verá que há duas portas lógicas no caminho, uma <code>OR</code> e uma <code>AND</code>. Uma das entradas da porta <code>OR</code> está ligada com o resultado da <code>AND</code> lá no fim do chip. Essa combinação faz com que, quando temos <strong>0</strong> e é nos dado um valor <strong>1</strong>, a porta <code>OR</code> vai resultar em <strong>1</strong>, e a <code>AND</code> também.</p>
<p>Porém, quando removemos o sinal do <code>set</code>, o valor que foi anteriormente colocado é persistido porque agora o <code>OR</code> está mantendo o estado que mantém o <code>AND</code> também no estado anterior. Problema resolvido, certo? Não! Perceba que nosso circuito agora está travado, pois não há como sair desse estado a não ser que o <code>AND</code> passe a ter um outro valor, e é para isso que serve a porta <code>reset</code>: ela está ligada a um <code>NOT</code>, ou seja, enquanto ela estiver desligada (0), o seu resultado vai ser 1 (ligado), e vice-versa.</p>
<p>Uma evolução que podemos fazer no <em><strong>flip-flop</strong></em> é transformá-lo em um <em><strong>Registrador</strong></em>. No registrador, podemos escolher se é ou não a hora de ler o nosso sinal e guardá-lo, e subsequentemente reescrevê-lo, e tudo isso ao nosso bel-prazer. Existem muitas formas de atingir esse chip, então vou usar a implementação demonstrada pelo <a href="https://www.youtube.com/watch?v=I0-izyq6q5s">Sebastian Lague</a>.</p>
<p>Nela, a gente só precisa adicionar mais 3 portas lógicas e pronto!</p>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/memory/">view it on the blog</a>.</em></p>
<pre><code>╭──────╮        ╭───╮     ╭───╮     ╭───╮     ╭───╮     ╭───╮     ╭───╮     ╭───╮     ╭───╮
│ data ├○──●───▶┤   │  ╭─▶┤NOT├○┬──▶┤NOT├○───▶┤   │ ╭──▶┤NOT├○╮ ╭▶┤   │ ╭──▶┤NOT├○●──▶┤LED│
╰──────╯   │    │AND├○─╯  ╰───╯ │   ╰───╯     │AND├○╯   ╰───╯ │ │ │AND├○╯   ╰───╯ │   ╰───╯
           │╭──▶┤   │           │           ╭▶┤   │           ╰─┼▶┤   │           │        
           ││   ╰───╯           │           │ ╰───╯             │ ╰───╯           │        
           ││                   ├───────────┼───────────────────╯                 │        
╭─────────╮││   ╭───╮     ╭───╮ │           │                                     │        
│ enabled ├○┼──▶┤NOT├○───▶┤   │ │           ╰─────────────────────────────────────╯        
╰─────────╯ │   ╰───╯     │AND├○╯                                                          
            ╰────────────▶┤   │                                                            
                          ╰───╯                                                            </code></pre>
<p>Se a gente destrinchar um pouco, o que acontece é o seguinte: a entrada superior, que agora chamaremos de <code>data</code>, só será salva no <em><strong>flip-flop</strong></em> quando a entrada inferior, que também mudou o nome, agora se chama <code>enabled</code>. Ou seja, em vez de usar duas entradas, uma para salvar e outra para apagar, essa combinação de <code>AND</code>s e <code>NOT</code> escolhe qual operação será feita.</p>
<ul>
<li>Se <code>data</code> = 1 e <code>enabled</code> = 1, então é a mesma coisa que ligar a entrada <code>set</code> do <em><strong>flip-flop</strong></em>.</li>
<li>Se <code>data</code> = 0 e <code>enabled</code> = 1, então é a mesma coisa que ligar a entrada <code>reset</code> do <em><strong>flip-flop</strong></em>.
Perceba que o <code>enabled</code> precisa sempre estar ativado para que possa salvar o sinal que foi colocado em <code>data</code>.</li>
</ul>
<p>Uma outra coisa que podemos fazer é pegar inspiração no artigo anterior, que no final a gente aprende que, se juntarmos vários Adders, nós podemos fazer contas com múltiplos dígitos. Na memória é do mesmo jeito: juntando vários registradores, você pode fornecer uma entrada para cada <code>data</code> e compartilhar o sinal do <code>enabled</code>, e assim você pode salvar os valores de um número binário inteiro.</p>
<p>Por enquanto, a gente se despede por aqui, até a próxima 😄</p>
<figure>
  <img src="https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExOXlucmJmbW5mZWp4MGRpOXhpZWZwczdma2xmemIxZGVjZ3hiZG5sciZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/m9eG1qVjvN56H0MXt8/giphy.gif" alt="Xauzinho!" loading="lazy">
  <figcaption>Xauzinho!</figcaption>
</figure><h2 id="referências">Referências</h2>
<ul>
<li><a href="https://www.youtube.com/watch?v=I0-izyq6q5s">How Do Computers Remember? (YouTube)</a></li>
<li><a href="https://www.youtube.com/watch?v=KM0DdEaY5sY">SR latch (YouTube)</a></li>
<li><a href="https://www.youtube.com/watch?v=peCh_859q7Q">D latch</a></li>
<li><a href="https://www.youtube.com/watch?v=HjneAhCy2N4">HOW TRANSISTORS RUN CODE? (YouTube)</a></li>
<li><a href="https://www.nand2tetris.org/">From Nand to Tetris</a></li>
</ul>
]]></content:encoded></item><item><title>Remember me?</title><link>https://jeffersonmourak.com/blog/memory-en/</link><pubDate>Sun, 19 Jan 2025 08:27:04 -0200</pubDate><guid>https://jeffersonmourak.com/blog/memory-en/</guid><category domain="https://jeffersonmourak.com/tags/cpu/">CPU</category><category domain="https://jeffersonmourak.com/tags/memory/">Memory</category><category domain="https://jeffersonmourak.com/tags/combinational/">Combinational</category><category domain="https://jeffersonmourak.com/tags/sequential/">Sequential</category><description>&lt;blockquote>
&lt;p>Hey Y&amp;rsquo;all! This is a translation of my blog post originally written in Portuguese.&lt;/p>&lt;/blockquote>
&lt;blockquote>
&lt;p>Hello everyone, this is the third article in the series about computers, and also the last one with this header here, because from here on it&amp;rsquo;s recommended that you have already read the two previous articles:&lt;/p>
&lt;ul>
&lt;li>&lt;a href="https://jeffersonmourak.com/blog/logic-gates/">Logic gates&lt;/a>.&lt;/li>
&lt;li>&lt;a href="https://jeffersonmourak.com/blog/the-binary/">Pleasure to meet you, Binary.&lt;/a>.&lt;/li>
&lt;/ul>&lt;/blockquote>
&lt;p>In the previous articles, we saw how logic gates can be used to make comparisons and also calculate arithmetic operations, but we haven&amp;rsquo;t yet seen how the computer can store information over time.&lt;/p></description><content:encoded><![CDATA[<blockquote>
<p>Hey Y&rsquo;all! This is a translation of my blog post originally written in Portuguese.</p></blockquote>
<blockquote>
<p>Hello everyone, this is the third article in the series about computers, and also the last one with this header here, because from here on it&rsquo;s recommended that you have already read the two previous articles:</p>
<ul>
<li><a href="https://jeffersonmourak.com/blog/logic-gates/">Logic gates</a>.</li>
<li><a href="https://jeffersonmourak.com/blog/the-binary/">Pleasure to meet you, Binary.</a>.</li>
</ul></blockquote>
<p>In the previous articles, we saw how logic gates can be used to make comparisons and also calculate arithmetic operations, but we haven&rsquo;t yet seen how the computer can store information over time.</p>
<p>Another thing we&rsquo;ll do here is categorize each type of chip: the ones shown previously are <em><strong>combinational</strong></em>, which means they don&rsquo;t need anything beyond signals at their inputs to be able to compute a result, but there are also <em><strong>sequential</strong></em> ones. The difference between them is that sequential depends not only on the input signals, but also on the previously processed value.</p>
<p>A very practical way to use logic gates to store information is using a chip called <em><strong>flip-flop</strong></em>, which is represented below. It contains 2 inputs: the top one <code>set</code> and the bottom one <code>reset</code> (you can click on the circuit below to interact with them).</p>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/memory-en/">view it on the blog</a>.</em></p>
<pre><code>╭───────╮     ╭───╮           ╭───╮     ╭───╮
│ reset ├○───▶┤NOT├○╮     ╭──▶┤   │ ╭──▶┤LED│
╰───────╯     ╰───╯ │     │   │AND├○●   ╰───╯
                    ╰─────┼──▶┤   │ │        
                          │   ╰───╯ │        
            ╭─────────────┼─────────╯        
╭─────╮     │ ╭─────────╮ │                  
│ set ├○╮   ╰▶┤         │ │                  
╰─────╯ │     │[or:_or_]├○╯                  
        ╰────▶┤         │                    
              ╰─────────╯                    </code></pre>
<p>If you stop to analyze, it&rsquo;s quite simple: following the <code>set</code> trail, you&rsquo;ll see there are two logic gates in the path, an <code>OR</code> and an <code>AND</code>. One of the <code>OR</code> gate inputs is connected to the result of the <code>AND</code> at the end of the chip. This combination makes it so that when we have <strong>0</strong> and are given a value <strong>1</strong>, the <code>OR</code> gate will result in <strong>1</strong>, and the <code>AND</code> will also.</p>
<p>However, when we remove the signal from <code>set</code>, the value that was previously placed is persisted because now the <code>OR</code> is maintaining the state that keeps the <code>AND</code> also in the previous state. Problem solved, right? No! Notice that our circuit is now locked, as there&rsquo;s no way to get out of this state unless the <code>AND</code> gets another value, and that&rsquo;s what the <code>reset</code> gate is for: it&rsquo;s connected to a <code>NOT</code>, meaning while it&rsquo;s off (0), its result will be 1 (on), and vice versa.</p>
<p>An evolution we can make to the <em><strong>flip-flop</strong></em> is to transform it into a <em><strong>Register</strong></em>. In the register, we can choose whether it&rsquo;s time or not to read our signal and store it, and subsequently rewrite it, all at our leisure. There are many ways to achieve this chip, so I&rsquo;ll use the implementation demonstrated by <a href="https://www.youtube.com/watch?v=I0-izyq6q5s">Sebastian Lague</a>.</p>
<p>In it, we just need to add 3 more logic gates and that&rsquo;s it!</p>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/memory-en/">view it on the blog</a>.</em></p>
<pre><code>╭──────╮        ╭───╮     ╭───╮     ╭───╮     ╭───╮     ╭───╮     ╭───╮     ╭───╮     ╭───╮
│ data ├○──●───▶┤   │  ╭─▶┤NOT├○┬──▶┤NOT├○───▶┤   │ ╭──▶┤NOT├○╮ ╭▶┤   │ ╭──▶┤NOT├○●──▶┤LED│
╰──────╯   │    │AND├○─╯  ╰───╯ │   ╰───╯     │AND├○╯   ╰───╯ │ │ │AND├○╯   ╰───╯ │   ╰───╯
           │╭──▶┤   │           │           ╭▶┤   │           ╰─┼▶┤   │           │        
           ││   ╰───╯           │           │ ╰───╯             │ ╰───╯           │        
           ││                   ├───────────┼───────────────────╯                 │        
╭─────────╮││   ╭───╮     ╭───╮ │           │                                     │        
│ enabled ├○┼──▶┤NOT├○───▶┤   │ │           ╰─────────────────────────────────────╯        
╰─────────╯ │   ╰───╯     │AND├○╯                                                          
            ╰────────────▶┤   │                                                            
                          ╰───╯                                                            </code></pre>
<p>If we break it down a bit, what happens is the following: the upper input, which we&rsquo;ll now call <code>data</code>, will only be saved in the <em><strong>flip-flop</strong></em> when the lower input, which also changed names, now called <code>enabled</code>. So instead of using two inputs, one to save and another to erase, this combination of <code>AND</code>s and <code>NOT</code> chooses which operation will be performed.</p>
<ul>
<li>If <code>data</code> = 1 and <code>enabled</code> = 1, then it&rsquo;s the same as turning on the <code>set</code> input of the <em><strong>flip-flop</strong></em>.</li>
<li>If <code>data</code> = 0 and <code>enabled</code> = 1, then it&rsquo;s the same as turning on the <code>reset</code> input of the <em><strong>flip-flop</strong></em>.
Notice that <code>enabled</code> always needs to be activated so that it can save the signal that was placed in <code>data</code>.</li>
</ul>
<p>Another thing we can do is take inspiration from the previous article, where at the end we learned that if we combine several Adders, we can do calculations with multiple digits. In memory it&rsquo;s the same way: combining several registers, you can provide an input for each <code>data</code> and share the <code>enabled</code> signal, and thus you can save the values of an entire binary number.</p>
<p>For now, we say goodbye here, see you next time 😄</p>
<figure>
  <img src="https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExOXlucmJmbW5mZWp4MGRpOXhpZWZwczdma2xmemIxZGVjZ3hiZG5sciZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/m9eG1qVjvN56H0MXt8/giphy.gif" alt="Bye bye!" loading="lazy">
  <figcaption>Bye bye!</figcaption>
</figure><h2 id="references">References</h2>
<ul>
<li><a href="https://www.youtube.com/watch?v=I0-izyq6q5s">How Do Computers Remember? (YouTube)</a></li>
<li><a href="https://www.youtube.com/watch?v=KM0DdEaY5sY">SR latch (YouTube)</a></li>
<li><a href="https://www.youtube.com/watch?v=peCh_859q7Q">D latch</a></li>
<li><a href="https://www.youtube.com/watch?v=HjneAhCy2N4">HOW TRANSISTORS RUN CODE? (YouTube)</a></li>
<li><a href="https://www.nand2tetris.org/">From Nand to Tetris</a></li>
</ul>
]]></content:encoded></item><item><title>Prazer, Binário.</title><link>https://jeffersonmourak.com/blog/the-binary/</link><pubDate>Sat, 14 Dec 2024 08:27:04 -0300</pubDate><guid>https://jeffersonmourak.com/blog/the-binary/</guid><category domain="https://jeffersonmourak.com/tags/cpu/">CPU</category><category domain="https://jeffersonmourak.com/tags/binary/">Binary</category><category domain="https://jeffersonmourak.com/tags/numeric-systems/">Numeric-Systems</category><category>Computação</category><category>Binário</category><description>&lt;blockquote>
&lt;p>Olá pessoas dessa internet, para quem está chegando aqui agora, este é o segundo artigo de
uma série que estou fazendo para falar sobre os fundamentos da computação, recomendo ler o
primeiro sobre &lt;a href="https://jeffersonmourak.com/blog/logic-gates/">portas lógicas&lt;/a>.
E para quem já leu o primeiro artigo, dá um pulinho lá porque eu fiz uma revisão no artigo, recomendo bastante dar uma olhada 😊&lt;/p>&lt;/blockquote>
&lt;p>Vamos nos aprofundar um pouco mais e explorar alguns conceitos de matemática e também da história humana.&lt;/p></description><content:encoded><![CDATA[<blockquote>
<p>Olá pessoas dessa internet, para quem está chegando aqui agora, este é o segundo artigo de
uma série que estou fazendo para falar sobre os fundamentos da computação, recomendo ler o
primeiro sobre <a href="https://jeffersonmourak.com/blog/logic-gates/">portas lógicas</a>.
E para quem já leu o primeiro artigo, dá um pulinho lá porque eu fiz uma revisão no artigo, recomendo bastante dar uma olhada 😊</p></blockquote>
<p>Vamos nos aprofundar um pouco mais e explorar alguns conceitos de matemática e também da história humana.</p>
<p>A matemática veio da necessidade de contar e medir da raça humana – quantos animais a Maria cuida, quantos dias até o próximo solstício&hellip; Com o tempo e a expansão humana, povos antigos criaram vários sistemas de numeração para o seu dia a dia. Jogos como <em>Grand Theft Auto V</em>, <em>Call of Duty: Black Ops III</em>, <em>Dragon Quest XI</em> são exemplos de uso do sistema numeral que os romanos usavam, e o <em>I Ching</em>, um antigo texto chinês, tem raízes em representações binárias.</p>
<p>Porém, não somente as antigas civilizações usavam outros sistemas numéricos. As horas de um dia são divididas entre 12 horas do período da manhã e 12 horas do período da tarde, ou uma dúzia de ovos. Na língua francesa ainda existem resquícios de um sistema com base vigesimal (20), por exemplo, o número 80 se diz <em>quatre-vingts</em> (quatro vintes), e um dos mais recentes é o Braille, que também tem raízes em representações binárias.</p>
<p>Nos dias atuais, utilizamos a representação decimal, e o motivo é bem simples: a média de dedos em mãos humanas são incríveis 10 dedos, sendo assim fica mais fácil contar usando somente as mãos.</p>
<h2 id="----">☝️ + ☝️ = ✌️</h2>
<p>Essa representação em base 10 é posicional, ou seja, a posição em que os dígitos são &ldquo;desenhados&rdquo; muda a quantidade que se está representando. <em>70</em> representa dez vezes mais que <em>07</em>, daí vem o ditado popular &ldquo;zero à esquerda&rdquo;. Na escola, aprendemos as casas decimais – <em>unidades</em>, <em>dezenas</em>, <em>centenas</em>&hellip; Elas servem para representar qual é a posição desse dígito.</p>
<table>
  <thead>
      <tr>
          <th style="text-align: center">Dezena</th>
          <th>Unidade</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td style="text-align: center">    7   </td>
          <td>0     </td>
      </tr>
      <tr>
          <td style="text-align: center">    0   </td>
          <td>7     </td>
      </tr>
  </tbody>
</table>
<p>E em cima dessa ordem existe uma fórmula matemática que converte um número de qualquer base para decimal. Para facilitar:</p>
<ul>
<li><strong>Dígito</strong>: Símbolo que representa uma quantidade única.
  <em>Ex.: 1, 2, 3, 4, 5, 6, 7, 8, 9, 0</em></li>
<li><strong>Número</strong>: Dígitos organizados em ordem de <em><strong>posição</strong></em>.
  <em>Ex.: 10, 144, 999, 42, 37, <code>0x8A6C</code>, <code>0b101010</code></em></li>
<li><strong>Base</strong>: Quantidade máxima de dígitos que pode ser representada.
  <em>Ex.: binário (<code>0b</code>) 2, decimal 10, hexadecimal (<code>0x</code>)</em></li>
<li><strong>Índice</strong>: A magnitude do dígito na posição.
  _Ex.: 10, o 1 em 10 tem <em>Índice 1</em> e o 0 tem <em>Índice 0</em> (é meio contraintuitivo, mas faz sentido).
  Em outras palavras, o índice é a posição da direita para a esquerda, começando em 0.</li>
</ul>
<p>A fórmula é bem simples: <em><strong>(d)ígito × (b)ase<sup>(i)ndice</sup></strong></em>. No exemplo que estamos fazendo, esta é a fórmula para converter 70 em decimal&hellip; para 70 em decimal. <strong>7 × 10<sup>1</sup> + 0 × 10<sup>0</sup> = 70</strong></p>
<p><em>Interactive binary counter widget (base 10, 3 digits) &mdash; <a href="https://jeffersonmourak.com/blog/the-binary/">view it on the blog</a>.</em></p>

<p>Quando falamos de números dessa forma, fica mais fácil representar o binário, que nada mais é que a quantidade que pode ser representada pela fórmula <em><strong>d × 2<sup>i</sup></strong></em>.</p>
<p><em>Interactive binary counter widget (base 2, 6 digits) &mdash; <a href="https://jeffersonmourak.com/blog/the-binary/">view it on the blog</a>.</em></p>

<p>E essa forma de representar quantidades também pode ser manipulada com operações matemáticas. A adição 25 + 17 é resolvida de modo parecido com isso.</p>
<pre tabindex="0"><code>1
2 5
1 7
--- +
4 2
</code></pre><p>No exemplo acima, temos alguns elementos que precisam ser destacados:</p>
<ol>
<li>Um <em>dígito</em> só pode ser somado com outro <em>dígito</em> que estiver no mesmo <em>índice</em>.</li>
<li>Quando a soma não puder ser representada com apenas um dígito, o menor índice é mantido como <em>resultado</em>, e o <em>resto</em> é enviado para o próximo índice.</li>
<li>O <em>resultado</em> de uma soma será sempre a soma dos <em><strong>dígitos</strong></em> do <em><strong>índice</strong></em> + o <em><strong>resto</strong></em> que veio do <em><strong>dígito</strong></em> no <em><strong>índice</strong></em> anterior.</li>
</ol>
<p>Com esses mesmos passos, podemos aplicar a soma em qualquer base.</p>
<pre tabindex="0"><code>    1 1 1       |  1      |  
1 0 0 0 1 1     |  2 5    |  1 9
0 0 0 1 1 1     |  1 7    |  1 1
------------ +  |  --- +  |  --- +
1 0 1 0 1 0     |  4 2    |  2 A 
</code></pre><figure>
  <img src="./hand.jpeg" alt="Cálculo de 25 &#43; 17 em bases Binária, Decimal e Hexadecimal" loading="lazy">
  <figcaption>Cálculo de 25 + 17 em bases Binária, Decimal e Hexadecimal</figcaption>
</figure><p><em>Interactive binary counter widget (base 2, 6 digits) &mdash; <a href="https://jeffersonmourak.com/blog/the-binary/">view it on the blog</a>.</em></p>

<p>Agora que já nos conhecemos, como podemos fazer para o computador nos conhecer também?</p>
<h2 id="brincando-de-tradução">Brincando de tradução</h2>
<p>Lembrando do <a href="https://jeffersonmourak.com/blog/logic-gates/">artigo anterior</a>, vamos isolar a soma de dois dígitos em tabelas. A primeira, vamos olhar para o resultado apenas. Temos esta tabela que se assemelha muito com a tabela da porta OR, exceto por essa pequena mudança no final.</p>
<div style="display: flex; gap: 16px;">
<span>
<table>
<tr><td colspan="3">Resultado</td></tr>
<tr>
 <td>?</td>
 <td>0</td>
 <td>1</td>
</tr>
<tr>
 <td>0</td>
 <td>0</td>
 <td>1</td>
</tr>
<tr>
 <td>1</td>
 <td>1</td>
 <td>0</td>
</tr>
</table>
</span>
<span>
<table>
<tr><td colspan="3">OR</td></tr>
<tr>
 <td>∨</td>
 <td>0</td>
 <td>1</td>
</tr>
<tr>
 <td>0</td>
 <td>0</td>
 <td>1</td>
</tr>
<tr>
 <td>1</td>
 <td>1</td>
 <td>1</td>
</tr>
</table>
</span>
</div>
<p>Para isso, podemos combinar o resultado das portas que já vimos anteriormente em um só circuito chamado &ldquo;OU Exclusivo&rdquo; ou &ldquo;XOR&rdquo;.</p>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/the-binary/">view it on the blog</a>.</em></p>
<pre><code>╭───╮     ╭─────────────╮     ╭───╮     ╭───╮
│ a ├○●●─▶┤             │╭───▶┤   │ ╭──▶┤LED│
╰───╯ ││  │[nand:_nand_]├○╮   │AND├○╯   ╰───╯
      │●─▶┤             ││╰──▶┤   │          
      ││  ╰─────────────╯│    ╰───╯          
      ││                 │                   
╭───╮ ││  ╭─────────╮    │                   
│ b ├○●╰─▶┤         │    │                   
╰───╯ │   │[or:_or_]├○───╯                   
      ╰──▶┤         │                        
          ╰─────────╯                        </code></pre>
<p>Agora, vamos olhar também para a tabela do resto da nossa soma e se percebe que é uma cópia exata da porta AND.</p>
<div style="display: flex; gap: 16px;">
<span>
<table>
<tr><td colspan="3">Resto</td></tr>
<tr>
 <td>?</td>
 <td>0</td>
 <td>1</td>
</tr>
<tr>
 <td>0</td>
 <td>0</td>
 <td>0</td>
</tr>
<tr>
 <td>1</td>
 <td>0</td>
 <td>1</td>
</tr>
</table>
</span>
<span>
<table>
<tr><td colspan="3">AND</td></tr>
<tr>
 <td>∧</td>
 <td>0</td>
 <td>1</td>
</tr>
<tr>
 <td>0</td>
 <td>0</td>
 <td>0</td>
</tr>
<tr>
 <td>1</td>
 <td>0</td>
 <td>1</td>
</tr>
</table>
</span>
</div>
<p>E assim como o Capitão Planeta, &ldquo;Pela união dos seus poderes&rdquo;, nós vamos conseguir fazer a operação de soma de dois dígitos em binário, e esse componente é chamado de &ldquo;Somador&rdquo; ou &ldquo;Adder&rdquo;.</p>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/the-binary/">view it on the blog</a>.</em></p>
<pre><code>╭───╮        ╭───╮               ╭───╮               ╭─────────╮     ╭───╮
│ a ├○●●────▶┤   │           ╭──▶┤   │ ╭────────────▶┤         │ ╭──▶┤LED│
╰───╯ ││     │AND├○╮         │   │AND├○╯             │[or:_or_]├○╯   ╰───╯
      │●────▶┤   │ │         │ ╭▶┤   │             ╭▶┤         │          
      ││     ╰───╯ │         │ │ ╰───╯             │ ╰─────────╯          
      ││           ╰─────────┼─┼───────────────────╯                      
╭───╮ ││     ╭─────────────╮ │ │ ╭─────────────╮                     ╭───╮
│ b ├○●╰────▶┤             │ ●─┼▶┤             │ ╭──────────────────▶┤LED│
╰───╯ │      │[xor:_xor_1_]├○● │ │[xor:_xor_2_]├○╯                   ╰───╯
      ╰─────▶┤             │   ●▶┤             │                          
             ╰─────────────╯   │ ╰─────────────╯                          
                               │                                          
╭──────╮                       │                                          
│ c_in ├○──────────────────────●                                          
╰──────╯                                                                  </code></pre>
<p>Com essa combinação de portas lógicas, um computador já consegue fazer as incríveis somas de: <code>0 + 0</code>, <code>1 + 0</code>, <code>0 + 1</code>, <code>1 + 1</code>, mas, além disso, ele consegue também dizer quanto que houve de resto da soma. E quando combinados vários ADDERs, a gente consegue fazer uma soma de números mais complexos como o 42, mas essa nós vamos ver no próximo artigo.</p>
<p>Por hoje é só isso, pessoal.</p>
<figure>
  <img src="https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaXg4ZHNiMjVkMG1nY3M3NjRhaDI5cmFoNWtmaHVxNDBweGV5ZjdwOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/xUPOqo6E1XvWXwlCyQ/giphy.gif" alt="Isso é tudo pessoal!" loading="lazy">
  <figcaption>Isso é tudo pessoal!</figcaption>
</figure><h2 id="referências">Referências</h2>
<ul>
<li><a href="https://pt.wikipedia.org/wiki/%C3%81lgebra_booliana">A brief history of numerical systems (Youtube)</a></li>
<li><a href="https://en.wikipedia.org/wiki/Numeral_system">Numeral system (Wikipédia)</a></li>
<li><a href="https://pt.wikipedia.org/wiki/Sistema_de_numera%C3%A7%C3%A3o">Sistema de numeração (Wikipédia)</a></li>
<li><a href="https://www.youtube.com/watch?v=QZwneRb-zqA">Exploring How Computers Work (YouTube)</a></li>
<li><a href="https://www.youtube.com/watch?v=sTu3LwpF6XI">Making logic gates from transistors (YouTube)</a></li>
<li><a href="https://www.youtube.com/watch?v=HjneAhCy2N4">HOW TRANSISTORS RUN CODE? (YouTube)</a></li>
<li><a href="https://www.nand2tetris.org/">From Nand to Tetris</a></li>
</ul>
]]></content:encoded></item><item><title>Pleasure to meet you, Binary.</title><link>https://jeffersonmourak.com/blog/the-binary-en/</link><pubDate>Sat, 14 Dec 2024 08:27:04 -0200</pubDate><guid>https://jeffersonmourak.com/blog/the-binary-en/</guid><category domain="https://jeffersonmourak.com/tags/cpu/">CPU</category><category domain="https://jeffersonmourak.com/tags/binary/">Binary</category><category domain="https://jeffersonmourak.com/tags/numeric-systems/">Numeric-Systems</category><category>Computing</category><description>&lt;blockquote>
&lt;p>Hey Y&amp;rsquo;all! This is a translation of my blog post originally written in Portuguese.&lt;/p>&lt;/blockquote>
&lt;blockquote>
&lt;p>Hello people of this internet, for those who are arriving here now, this is the second article of
a series I&amp;rsquo;m doing to talk about the fundamentals of computing, I recommend reading the
first one about &lt;a href="https://jeffersonmourak.com/blog/logic-gates/">logic gates&lt;/a>.
And for those who have already read the first article, take a quick look there because I did a revision of the article, I highly recommend taking a look 😊&lt;/p></description><content:encoded><![CDATA[<blockquote>
<p>Hey Y&rsquo;all! This is a translation of my blog post originally written in Portuguese.</p></blockquote>
<blockquote>
<p>Hello people of this internet, for those who are arriving here now, this is the second article of
a series I&rsquo;m doing to talk about the fundamentals of computing, I recommend reading the
first one about <a href="https://jeffersonmourak.com/blog/logic-gates/">logic gates</a>.
And for those who have already read the first article, take a quick look there because I did a revision of the article, I highly recommend taking a look 😊</p></blockquote>
<p>Let&rsquo;s dive a bit deeper and explore some concepts of mathematics and also human history.</p>
<p>Mathematics came from the human race&rsquo;s need to count and measure – how many animals Maria takes care of, how many days until the next solstice&hellip; Over time and human expansion, ancient peoples created various numbering systems for their daily lives. Games like <em>Grand Theft Auto V</em>, <em>Call of Duty: Black Ops III</em>, <em>Dragon Quest XI</em> are examples of using the numeral system that the Romans used, and the <em>I Ching</em>, an ancient Chinese text, has roots in binary representations.</p>
<p>However, not only ancient civilizations used other numerical systems. The hours of a day are divided between 12 hours of the morning period and 12 hours of the afternoon period, or a dozen eggs. In the French language, there are still remnants of a vigesimal-based system (20), for example, the number 80 is said as <em>quatre-vingts</em> (four twenties), and one of the most recent is Braille, which also has roots in binary representations.</p>
<p>Nowadays, we use decimal representation, and the reason is quite simple: the average number of fingers on human hands is an incredible 10 fingers, so it&rsquo;s easier to count using only hands.</p>
<h2 id="----">☝️ + ☝️ = ✌️</h2>
<p>This base 10 representation is positional, meaning the position in which the digits are &ldquo;drawn&rdquo; changes the quantity being represented. <em>70</em> represents ten times more than <em>07</em>, hence the popular saying &ldquo;zero to the left&rdquo;. In school, we learn about decimal places – <em>units</em>, <em>tens</em>, <em>hundreds</em>&hellip; They serve to represent what the position of that digit is.</p>
<table>
  <thead>
      <tr>
          <th style="text-align: center">Tens</th>
          <th>Units</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td style="text-align: center">7</td>
          <td>0</td>
      </tr>
      <tr>
          <td style="text-align: center">0</td>
          <td>7</td>
      </tr>
  </tbody>
</table>
<p>And on top of this order, there&rsquo;s a mathematical formula that converts a number from any base to decimal. To make it easier:</p>
<ul>
<li><strong>Digit</strong>: Symbol that represents a unique quantity.
<em>Ex.: 1, 2, 3, 4, 5, 6, 7, 8, 9, 0</em></li>
<li><strong>Number</strong>: Digits organized in order of <em><strong>position</strong></em>.
<em>Ex.: 10, 144, 999, 42, 37, <code>0x8A6C</code>, <code>0b101010</code></em></li>
<li><strong>Base</strong>: Maximum quantity of digits that can be represented.
<em>Ex.: binary (<code>0b</code>) 2, decimal 10, hexadecimal (<code>0x</code>)</em></li>
<li><strong>Index</strong>: The magnitude of the digit in the position.
_Ex.: 10, the 1 in 10 has <em>Index 1</em> and the 0 has <em>Index 0</em> (it&rsquo;s a bit counterintuitive, but it makes sense).
In other words, the index is the position from right to left, starting at 0.</li>
</ul>
<p>The formula is quite simple: <em><strong>(d)igit × (b)ase<sup>(i)ndex</sup></strong></em>. In the example we&rsquo;re doing, this is the formula to convert 70 to decimal&hellip; to 70 in decimal. <strong>7 × 10<sup>1</sup> + 0 × 10<sup>0</sup> = 70</strong></p>
<p><em>Interactive binary counter widget (base 10, 3 digits) &mdash; <a href="https://jeffersonmourak.com/blog/the-binary-en/">view it on the blog</a>.</em></p>

<p>When we talk about numbers this way, it becomes easier to represent binary, which is nothing more than the quantity that can be represented by the formula <em><strong>d × 2<sup>i</sup></strong></em>.</p>
<p><em>Interactive binary counter widget (base 2, 6 digits) &mdash; <a href="https://jeffersonmourak.com/blog/the-binary-en/">view it on the blog</a>.</em></p>

<p>And this way of representing quantities can also be manipulated with mathematical operations. The addition 25 + 17 is solved in a way similar to this.</p>
<pre tabindex="0"><code>1
2 5
1 7
--- +
4 2
</code></pre><p>In the example above, we have some elements that need to be highlighted:</p>
<ol>
<li>A <em>digit</em> can only be added to another <em>digit</em> that is in the same <em>index</em>.</li>
<li>When the sum cannot be represented with just one digit, the smallest index is kept as the <em>result</em>, and the <em>remainder</em> is sent to the next index.</li>
<li>The <em>result</em> of a sum will always be the sum of the <em><strong>digits</strong></em> of the <em><strong>index</strong></em> + the <em><strong>remainder</strong></em> that came from the <em><strong>digit</strong></em> in the previous <em><strong>index</strong></em>.</li>
</ol>
<p>With these same steps, we can apply addition in any base.</p>
<pre tabindex="0"><code>    1 1 1       |  1      |  
1 0 0 0 1 1     |  2 5    |  1 9
0 0 0 1 1 1     |  1 7    |  1 1
------------ +  |  --- +  |  --- +
1 0 1 0 1 0     |  4 2    |  2 A 
</code></pre><figure>
  <img src="./hand.jpeg" alt="Calculation of 25 &#43; 17 in Binary, Decimal and Hexadecimal bases" loading="lazy">
  <figcaption>Calculation of 25 + 17 in Binary, Decimal and Hexadecimal bases</figcaption>
</figure><p><em>Interactive binary counter widget (base 2, 6 digits) &mdash; <a href="https://jeffersonmourak.com/blog/the-binary-en/">view it on the blog</a>.</em></p>

<p>Now that we already know each other, how can we make the computer know us too?</p>
<h2 id="playing-with-translation">Playing with translation</h2>
<p>Remembering the <a href="https://jeffersonmourak.com/blog/logic-gates/">previous article</a>, let&rsquo;s isolate the addition of two digits in tables. First, let&rsquo;s look at just the result. We have this table that very much resembles the OR gate table, except for this small change at the end.</p>
<div style="display: flex; gap: 16px;">
<span>
<table>
<tr><td colspan="3">Result</td></tr>
<tr>
 <td>?</td>
 <td>0</td>
 <td>1</td>
</tr>
<tr>
 <td>0</td>
 <td>0</td>
 <td>1</td>
</tr>
<tr>
 <td>1</td>
 <td>1</td>
 <td>0</td>
</tr>
</table>
</span>
<span>
<table>
<tr><td colspan="3">OR</td></tr>
<tr>
 <td>∨</td>
 <td>0</td>
 <td>1</td>
</tr>
<tr>
 <td>0</td>
 <td>0</td>
 <td>1</td>
</tr>
<tr>
 <td>1</td>
 <td>1</td>
 <td>1</td>
</tr>
</table>
</span>
</div>
<p>For this, we can combine the results of the gates we saw earlier into a single circuit called &ldquo;Exclusive OR&rdquo; or &ldquo;XOR&rdquo;.</p>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/the-binary-en/">view it on the blog</a>.</em></p>
<pre><code>╭───╮     ╭─────────────╮     ╭───╮     ╭───╮
│ a ├○●●─▶┤             │╭───▶┤   │ ╭──▶┤LED│
╰───╯ ││  │[nand:_nand_]├○╮   │AND├○╯   ╰───╯
      │●─▶┤             ││╰──▶┤   │          
      ││  ╰─────────────╯│    ╰───╯          
      ││                 │                   
╭───╮ ││  ╭─────────╮    │                   
│ b ├○●╰─▶┤         │    │                   
╰───╯ │   │[or:_or_]├○───╯                   
      ╰──▶┤         │                        
          ╰─────────╯                        </code></pre>
<p>Now, let&rsquo;s also look at the remainder table of our addition and you&rsquo;ll notice that it&rsquo;s an exact copy of the AND gate.</p>
<div style="display: flex; gap: 16px;">
<span>
<table>
<tr><td colspan="3">Remainder</td></tr>
<tr>
 <td>?</td>
 <td>0</td>
 <td>1</td>
</tr>
<tr>
 <td>0</td>
 <td>0</td>
 <td>0</td>
</tr>
<tr>
 <td>1</td>
 <td>0</td>
 <td>1</td>
</tr>
</table>
</span>
<span>
<table>
<tr><td colspan="3">AND</td></tr>
<tr>
 <td>∧</td>
 <td>0</td>
 <td>1</td>
</tr>
<tr>
 <td>0</td>
 <td>0</td>
 <td>0</td>
</tr>
<tr>
 <td>1</td>
 <td>0</td>
 <td>1</td>
</tr>
</table>
</span>
</div>
<p>And just like Captain Planet, &ldquo;By the union of their powers&rdquo;, we will be able to perform the operation of adding two digits in binary, and this component is called &ldquo;Adder&rdquo;.</p>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/the-binary-en/">view it on the blog</a>.</em></p>
<pre><code>╭───╮        ╭───╮               ╭───╮               ╭─────────╮     ╭───╮
│ a ├○●●────▶┤   │           ╭──▶┤   │ ╭────────────▶┤         │ ╭──▶┤LED│
╰───╯ ││     │AND├○╮         │   │AND├○╯             │[or:_or_]├○╯   ╰───╯
      │●────▶┤   │ │         │ ╭▶┤   │             ╭▶┤         │          
      ││     ╰───╯ │         │ │ ╰───╯             │ ╰─────────╯          
      ││           ╰─────────┼─┼───────────────────╯                      
╭───╮ ││     ╭─────────────╮ │ │ ╭─────────────╮                     ╭───╮
│ b ├○●╰────▶┤             │ ●─┼▶┤             │ ╭──────────────────▶┤LED│
╰───╯ │      │[xor:_xor_1_]├○● │ │[xor:_xor_2_]├○╯                   ╰───╯
      ╰─────▶┤             │   ●▶┤             │                          
             ╰─────────────╯   │ ╰─────────────╯                          
                               │                                          
╭──────╮                       │                                          
│ c_in ├○──────────────────────●                                          
╰──────╯                                                                  </code></pre>
<p>With this combination of logic gates, a computer can already perform the incredible additions of: <code>0 + 0</code>, <code>1 + 0</code>, <code>0 + 1</code>, <code>1 + 1</code>, but beyond that, it can also say how much remainder there was from the addition. And when several ADDERs are combined, we can perform addition of more complex numbers like 42, but that we&rsquo;ll see in the next article.</p>
<p>That&rsquo;s all for today, folks.
<img src="https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaXg4ZHNiMjVkMG1nY3M3NjRhaDI5cmFoNWtmaHVxNDBweGV5ZjdwOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/xUPOqo6E1XvWXwlCyQ/giphy.gif" alt="That&rsquo;s all folks!" loading="lazy"></p>
<h2 id="references">References</h2>
<ul>
<li><a href="https://pt.wikipedia.org/wiki/%C3%81lgebra_booliana">A brief history of numerical systems (Youtube)</a></li>
<li><a href="https://en.wikipedia.org/wiki/Numeral_system">Numeral system (Wikipédia)</a></li>
<li><a href="https://pt.wikipedia.org/wiki/Sistema_de_numera%C3%A7%C3%A3o">Sistema de numeração (Wikipédia)</a></li>
<li><a href="https://www.youtube.com/watch?v=QZwneRb-zqA">Exploring How Computers Work (YouTube)</a></li>
<li><a href="https://www.youtube.com/watch?v=sTu3LwpF6XI">Making logic gates from transistors (YouTube)</a></li>
<li><a href="https://www.youtube.com/watch?v=HjneAhCy2N4">HOW TRANSISTORS RUN CODE? (YouTube)</a></li>
<li><a href="https://www.nand2tetris.org/">From Nand to Tetris</a></li>
</ul>
]]></content:encoded></item><item><title>Portas lógicas</title><link>https://jeffersonmourak.com/blog/logic-gates/</link><pubDate>Thu, 07 Nov 2024 08:27:04 -0300</pubDate><guid>https://jeffersonmourak.com/blog/logic-gates/</guid><category domain="https://jeffersonmourak.com/tags/cpu/">CPU</category><category domain="https://jeffersonmourak.com/tags/logic-gates/">Logic Gates</category><category>Portas lógicas</category><category>Computação</category><description>&lt;blockquote>
&lt;p>Revisado [11/12/2024]&lt;/p>
&lt;p>Oi pessoal, então tive que fazer umas mudanças aqui no post pra adicionar alguns widgets
interativos, e aproveitei para dar um pouco mais de contexto ao conteúdo.&lt;/p>&lt;/blockquote>
&lt;p>Olá, este é o primeiro artigo de uma série sobre os fundamentos da computação. A ideia é demonstrar de forma simples e prática como este dispositivo transforma zeros e uns em praticamente qualquer coisa, o funcionamento das CPUs e outros assuntos interessantes. Então, para começar, o primeiro conceito que temos que aprender é o de portas lógicas: elas são a base de toda a computação, com elas podemos fazer certas operações que recebem como entrada um ou mais valores e terão outro valor como resultado.&lt;/p></description><content:encoded><![CDATA[<blockquote>
<p>Revisado [11/12/2024]</p>
<p>Oi pessoal, então tive que fazer umas mudanças aqui no post pra adicionar alguns widgets
interativos, e aproveitei para dar um pouco mais de contexto ao conteúdo.</p></blockquote>
<p>Olá, este é o primeiro artigo de uma série sobre os fundamentos da computação. A ideia é demonstrar de forma simples e prática como este dispositivo transforma zeros e uns em praticamente qualquer coisa, o funcionamento das CPUs e outros assuntos interessantes. Então, para começar, o primeiro conceito que temos que aprender é o de portas lógicas: elas são a base de toda a computação, com elas podemos fazer certas operações que recebem como entrada um ou mais valores e terão outro valor como resultado.</p>
<p>Mas o que são esses valores? O número 42? O nome da minha mãe? Esses “valores” são energia, mais especificamente a presença e ausência dela. Como foi falado na introdução, computadores funcionam utilizando dígitos binários, ou seja, essas máquinas só entendem 0 e 1 ou “Tem energia” e “Não tem energia”. No entanto, não iremos chamar esses zeros e uns de energia, para o computador eles são sinais.</p>
<p>Quando sinais são combinados e/ou comparados, nós chamamos de operação lógica, por exemplo.</p>
<p>“[Sons de harpa de inicio de história]”</p>
<p>Um dia você contrata uma empresa de elétrica para instalar dois interruptores em um corredor da sua casa, mas, por um erro de desenho, a instalação acaba ficando da seguinte forma: o fio passa pelo primeiro interruptor (vamos chamar de interruptor A), vai direto para o segundo interruptor (B para os íntimos) e, em seguida, sai para a lâmpada.</p>
<figure>
  <img src="./CPUImageFrame1.png" alt="" loading="lazy">
</figure><p>Reparou que a lâmpada só acende se os dois interruptores estiverem ligados ao mesmo tempo? Se qualquer um deles for desligado, a luz apaga na hora! Pois é, essa atrocidade da elétrica residencial pode ser explicada, na matemática, a partir de um de seus ramos chamado de álgebra booleana, e nela podemos demonstrar isso com uma tabela:</p>
<table>
  <thead>
      <tr>
          <th style="text-align: center">∧</th>
          <th style="text-align: center">0</th>
          <th style="text-align: center">1</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td style="text-align: center">0</td>
          <td style="text-align: center">0</td>
          <td style="text-align: center">0</td>
      </tr>
      <tr>
          <td style="text-align: center">1</td>
          <td style="text-align: center">0</td>
          <td style="text-align: center">1</td>
      </tr>
  </tbody>
</table>
<p>Escrevendo isso de outro modo fica assim:</p>
<table>
  <thead>
      <tr>
          <th style="text-align: left">∧</th>
          <th style="text-align: left">A desligado</th>
          <th style="text-align: left">A ligado</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td style="text-align: left">B desligado</td>
          <td style="text-align: left">Luz apagada</td>
          <td style="text-align: left">Luz apagada</td>
      </tr>
      <tr>
          <td style="text-align: left">B ligado</td>
          <td style="text-align: left">Luz apagada</td>
          <td style="text-align: left">Luz acesa</td>
      </tr>
  </tbody>
</table>
<p>Se você percebeu bem, agora temos um jeito de representar o que queremos que aconteça com dois interruptores e uma lâmpada, e esse exemplo mostrado acima é a primeira porta lógica que estamos conhecendo, o AND ou Conjunção, e essa tabela, demonstrada acima de formas diferentes, se chama Tabela-Verdade.</p>
<p>Ok, mas e a luz da minha casa? Como que vai ficar? Eu preciso que a luz acenda quando o A OU B estiverem ligados. Como que faz isso?</p>
<p>A resposta está na própria pergunta! 😉 Vamos precisar de uma outra porta lógica, a OR ou Disjunção, e para entender como ela funciona, vamos usar uma tabela-verdade que se encaixe nessas condições:</p>
<table>
  <thead>
      <tr>
          <th style="text-align: center">?</th>
          <th style="text-align: center">0</th>
          <th style="text-align: center">1</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td style="text-align: center">0</td>
          <td style="text-align: center">0</td>
          <td style="text-align: center">1</td>
      </tr>
      <tr>
          <td style="text-align: center">1</td>
          <td style="text-align: center">1</td>
          <td style="text-align: center">1</td>
      </tr>
  </tbody>
</table>
<p>Mas antes de falar da OR, vamos dar uma olhada na porta NOT (ou Negação). Ela é bem simples, mas vai ser importante mais pra frente.</p>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/logic-gates/">view it on the blog</a>.</em></p>
<pre><code>╭───╮     ╭───╮     ╭───╮
│ a ├○───▶┤NOT├○───▶┤LED│
╰───╯     ╰───╯     ╰───╯</code></pre>
<p>E se escrevermos ela numa tabela verdade teremos isso aqui:</p>
<table>
  <thead>
      <tr>
          <th style="text-align: center">¬</th>
          <th style="text-align: center">0</th>
          <th style="text-align: center">1</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td style="text-align: center"></td>
          <td style="text-align: center">1</td>
          <td style="text-align: center">0</td>
      </tr>
  </tbody>
</table>
<p>Então, vamos fazer uma pausa e revisar o que a gente já sabe. Primeiro, as operações e como representá-las numa tabela. Para simplificar, vamos transformar essas operações em símbolos. Toda vez que nos referirmos ao AND, este será o símbolo:</p>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/logic-gates/">view it on the blog</a>.</em></p>
<pre><code>╭───╮     ╭───╮     ╭───╮
│ a ├○───▶┤   │ ╭──▶┤LED│
╰───╯     │AND├○╯   ╰───╯
       ╭─▶┤   │          
       │  ╰───╯          
       │                 
╭───╮  │                 
│ b ├○─╯                 
╰───╯                    </code></pre>
<p>e o NOT:</p>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/logic-gates/">view it on the blog</a>.</em></p>
<pre><code>╭───╮     ╭───╮     ╭───╮
│ a ├○───▶┤NOT├○───▶┤LED│
╰───╯     ╰───╯     ╰───╯</code></pre>
<p>Com essas duas operações lógicas (AND e NOT), já podemos combinar seus resultados e criar uma terceira porta lógica: a NAND (ou Not AND).</p>
<p>Ela pode ser representada assim:</p>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/logic-gates/">view it on the blog</a>.</em></p>
<pre><code>╭───╮     ╭─────────────╮     ╭───╮
│ a ├○───▶┤             │ ╭──▶┤LED│
╰───╯     │[nand:_nand_]├○╯   ╰───╯
       ╭─▶┤             │          
       │  ╰─────────────╯          
       │                           
╭───╮  │                           
│ b ├○─╯                           
╰───╯                              </code></pre>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/logic-gates/">view it on the blog</a>.</em></p>
<pre><code>╭───╮     ╭───╮     ╭───╮     ╭───╮
│ a ├○───▶┤   │ ╭──▶┤NOT├○───▶┤LED│
╰───╯     │AND├○╯   ╰───╯     ╰───╯
       ╭─▶┤   │                    
       │  ╰───╯                    
       │                           
╭───╮  │                           
│ b ├○─╯                           
╰───╯                              </code></pre>
<p>A tabela-verdade dela é idêntica à do AND, porém com os resultados invertidos.</p>
<table>
  <thead>
      <tr>
          <th style="text-align: center">¬∧</th>
          <th style="text-align: center">0</th>
          <th style="text-align: center">1</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td style="text-align: center">0</td>
          <td style="text-align: center">1</td>
          <td style="text-align: center">1</td>
      </tr>
      <tr>
          <td style="text-align: center">1</td>
          <td style="text-align: center">1</td>
          <td style="text-align: center">0</td>
      </tr>
  </tbody>
</table>
<p>Seguindo essa mesma lógica de combinar portas, podemos usar uma porta NAND e inverter a entrada de cada interruptor com um NOT. Assim, teremos o seguinte:</p>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/logic-gates/">view it on the blog</a>.</em></p>
<pre><code>╭───╮     ╭───╮     ╭─────────────╮     ╭───╮
│ a ├○───▶┤NOT├○───▶┤             │ ╭──▶┤LED│
╰───╯     ╰───╯     │[nand:_nand_]├○╯   ╰───╯
                 ╭─▶┤             │          
                 │  ╰─────────────╯          
                 │                           
╭───╮     ╭───╮  │                           
│ b ├○───▶┤NOT├○─╯                           
╰───╯     ╰───╯                              </code></pre>
<p>Analisando o diagrama acima, vemos que, quando os dois interruptores estiverem desligados, ambos os sinais serão invertidos pelo NOT, e o NAND vai resultar em ¬∧(1, 1) = 0. Ou seja, com ambos desligados, a lâmpada apaga. Mas o que acontece quando temos ¬∧(1, 0) ou ¬∧(0, 1)? Para descobrir, vamos analisar a tabela-verdade:</p>
<table>
  <thead>
      <tr>
          <th style="text-align: center">∨</th>
          <th style="text-align: center">0</th>
          <th style="text-align: center">1</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td style="text-align: center">0</td>
          <td style="text-align: center">0</td>
          <td style="text-align: center">1</td>
      </tr>
      <tr>
          <td style="text-align: center">1</td>
          <td style="text-align: center">1</td>
          <td style="text-align: center">1</td>
      </tr>
  </tbody>
</table>
<figure>
  <img src="https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExa2F3aTZ5Z2FhajUxem51aG5oYzBwYW1jdHI3NGswMzZzd3duMTh3biZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n9h61thJkq6Xe/giphy.gif" alt="Eu acho que vi um gatinho!" loading="lazy">
  <figcaption>Eu acho que vi um gatinho!</figcaption>
</figure><p>Mas espera um pouco, eu tenho a impressão de que eu já vi essa tabela antes? Sim! Essa é a porta lógica OR que estávamos procurando. Uma viagem e tanto, não é? Agora que já sabemos como consertar a fiação da lâmpada, podemos dar uma paradinha aqui. Este é apenas o primeiro artigo de uma série sobre computadores. Mais para frente, vamos abordar outras portas lógicas e outros conceitos da computação.</p>
<h2 id="referências">Referências</h2>
<ul>
<li><a href="https://pt.wikipedia.org/wiki/%C3%81lgebra_booliana">Álgebra booliana (Wikipédia)</a></li>
<li><a href="https://en.wikipedia.org/wiki/Boolean_algebra">Boolean Algebra (Wikipédia)</a></li>
<li><a href="https://pt.wikipedia.org/wiki/Tabela-verdade">Tabela-verdade  (Wikipédia)</a></li>
<li><a href="https://www.youtube.com/watch?v=QZwneRb-zqA">Exploring How Computers Work (YouTube)</a></li>
<li><a href="https://www.youtube.com/watch?v=sTu3LwpF6XI">Making logic gates from transistors (YouTube)</a></li>
<li><a href="https://www.youtube.com/watch?v=HjneAhCy2N4">HOW TRANSISTORS RUN CODE? (YouTube)</a></li>
</ul>
]]></content:encoded></item><item><title>Logic Gates</title><link>https://jeffersonmourak.com/blog/logic-gates-en/</link><pubDate>Thu, 07 Nov 2024 08:27:04 -0200</pubDate><guid>https://jeffersonmourak.com/blog/logic-gates-en/</guid><category domain="https://jeffersonmourak.com/tags/cpu/">CPU</category><category domain="https://jeffersonmourak.com/tags/logic-gates/">Logic Gates</category><category>Computing</category><description>&lt;blockquote>
&lt;p>Hey Y&amp;rsquo;all! This is a translation of my blog post originally written in Portuguese.&lt;/p>&lt;/blockquote>
&lt;blockquote>
&lt;p>Revised [11/12/2024]&lt;/p>
&lt;p>Hi folks, so I had to make some changes here in the post to add some interactive widgets,
and I took the opportunity to give a bit more context to the content.&lt;/p>&lt;/blockquote>
&lt;p>Hello, this is the first article in a series about the fundamentals of computing. The idea is to demonstrate in a simple and practical way how this device transforms zeros and ones into practically anything, the functioning of CPUs and other interesting subjects. So, to start, the first concept we have to learn is that of logic gates: they are the foundation of all computing, with them we can do certain operations that receive as input one or more values and will have another value as a result.&lt;/p></description><content:encoded><![CDATA[<blockquote>
<p>Hey Y&rsquo;all! This is a translation of my blog post originally written in Portuguese.</p></blockquote>
<blockquote>
<p>Revised [11/12/2024]</p>
<p>Hi folks, so I had to make some changes here in the post to add some interactive widgets,
and I took the opportunity to give a bit more context to the content.</p></blockquote>
<p>Hello, this is the first article in a series about the fundamentals of computing. The idea is to demonstrate in a simple and practical way how this device transforms zeros and ones into practically anything, the functioning of CPUs and other interesting subjects. So, to start, the first concept we have to learn is that of logic gates: they are the foundation of all computing, with them we can do certain operations that receive as input one or more values and will have another value as a result.</p>
<p>But what are these values? The number 42? My mother&rsquo;s name? These &ldquo;values&rdquo; are energy, more specifically the presence and absence of it. As mentioned in the introduction, computers work using binary digits, meaning these machines only understand 0 and 1 or &ldquo;Has energy&rdquo; and &ldquo;No energy&rdquo;. However, we won&rsquo;t call these zeros and ones energy, for the computer they are signals.</p>
<p>When signals are combined and/or compared, we call it a logical operation, for example.</p>
<p>&ldquo;[Harp sounds of story beginning]&rdquo;</p>
<p>One day you hire an electrical company to install two switches in a hallway of your house, but due to a design error, the installation ends up like this: the wire passes through the first switch (let&rsquo;s call it switch A), goes straight to the second switch (B for intimates) and then exits to the lamp.</p>
<figure>
  <img src="./CPUImageFrame1.png" alt="" loading="lazy">
</figure><p>Did you notice that the lamp only lights up if both switches are on at the same time? If either one is turned off, the light goes out immediately! Well, this residential electrical atrocity can be explained, in mathematics, from one of its branches called boolean algebra, and in it we can demonstrate this with a table:</p>
<table>
  <thead>
      <tr>
          <th style="text-align: center">∧</th>
          <th style="text-align: center">0</th>
          <th style="text-align: center">1</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td style="text-align: center">0</td>
          <td style="text-align: center">0</td>
          <td style="text-align: center">0</td>
      </tr>
      <tr>
          <td style="text-align: center">1</td>
          <td style="text-align: center">0</td>
          <td style="text-align: center">1</td>
      </tr>
  </tbody>
</table>
<p>Writing this another way looks like this:</p>
<table>
  <thead>
      <tr>
          <th style="text-align: left">∧</th>
          <th style="text-align: left">A off</th>
          <th style="text-align: left">A on</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td style="text-align: left">B off</td>
          <td style="text-align: left">Light off</td>
          <td style="text-align: left">Light off</td>
      </tr>
      <tr>
          <td style="text-align: left">B on</td>
          <td style="text-align: left">Light off</td>
          <td style="text-align: left">Light on</td>
      </tr>
  </tbody>
</table>
<p>If you noticed well, now we have a way to represent what we want to happen with two switches and a lamp, and this example shown above is the first logic gate we&rsquo;re getting to know, the AND or Conjunction, and this table, demonstrated above in different forms, is called a Truth Table.</p>
<p>Ok, but what about my house light? How is it going to be? I need the light to turn on when A OR B is on. How do you do that?</p>
<p>The answer is in the question itself! 😉 We&rsquo;ll need another logic gate, the OR or Disjunction, and to understand how it works, let&rsquo;s use a truth table that fits these conditions:</p>
<table>
  <thead>
      <tr>
          <th style="text-align: center">?</th>
          <th style="text-align: center">0</th>
          <th style="text-align: center">1</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td style="text-align: center">0</td>
          <td style="text-align: center">0</td>
          <td style="text-align: center">1</td>
      </tr>
      <tr>
          <td style="text-align: center">1</td>
          <td style="text-align: center">1</td>
          <td style="text-align: center">1</td>
      </tr>
  </tbody>
</table>
<p>But before talking about OR, let&rsquo;s take a look at the NOT gate (or Negation). It&rsquo;s quite simple, but it will be important later on.</p>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/logic-gates-en/">view it on the blog</a>.</em></p>
<pre><code>╭───╮     ╭───╮     ╭───╮
│ a ├○───▶┤NOT├○───▶┤LED│
╰───╯     ╰───╯     ╰───╯</code></pre>
<p>And if we write it in a truth table we&rsquo;ll have this here:</p>
<table>
  <thead>
      <tr>
          <th style="text-align: center">¬</th>
          <th style="text-align: center">0</th>
          <th style="text-align: center">1</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td style="text-align: center"></td>
          <td style="text-align: center">1</td>
          <td style="text-align: center">0</td>
      </tr>
  </tbody>
</table>
<p>So, let&rsquo;s take a break and review what we already know. First, the operations and how to represent them in a table. To simplify, let&rsquo;s transform these operations into symbols. Every time we refer to AND, this will be the symbol:</p>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/logic-gates-en/">view it on the blog</a>.</em></p>
<pre><code>╭───╮     ╭───╮     ╭───╮
│ a ├○───▶┤   │ ╭──▶┤LED│
╰───╯     │AND├○╯   ╰───╯
       ╭─▶┤   │          
       │  ╰───╯          
       │                 
╭───╮  │                 
│ b ├○─╯                 
╰───╯                    </code></pre>
<p>and the NOT:</p>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/logic-gates-en/">view it on the blog</a>.</em></p>
<pre><code>╭───╮     ╭───╮     ╭───╮
│ a ├○───▶┤NOT├○───▶┤LED│
╰───╯     ╰───╯     ╰───╯</code></pre>
<p>With these two logical operations (AND and NOT), we can already combine their results and create a third logic gate: the NAND (or Not AND).</p>
<p>It can be represented like this:</p>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/logic-gates-en/">view it on the blog</a>.</em></p>
<pre><code>╭───╮     ╭─────────────╮     ╭───╮
│ a ├○───▶┤             │ ╭──▶┤LED│
╰───╯     │[nand:_nand_]├○╯   ╰───╯
       ╭─▶┤             │          
       │  ╰─────────────╯          
       │                           
╭───╮  │                           
│ b ├○─╯                           
╰───╯                              </code></pre>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/logic-gates-en/">view it on the blog</a>.</em></p>
<pre><code>╭───╮     ╭───╮     ╭───╮     ╭───╮
│ a ├○───▶┤   │ ╭──▶┤NOT├○───▶┤LED│
╰───╯     │AND├○╯   ╰───╯     ╰───╯
       ╭─▶┤   │                    
       │  ╰───╯                    
       │                           
╭───╮  │                           
│ b ├○─╯                           
╰───╯                              </code></pre>
<p>Its truth table is identical to AND&rsquo;s, but with the results inverted.</p>
<table>
  <thead>
      <tr>
          <th style="text-align: center">¬∧</th>
          <th style="text-align: center">0</th>
          <th style="text-align: center">1</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td style="text-align: center">0</td>
          <td style="text-align: center">1</td>
          <td style="text-align: center">1</td>
      </tr>
      <tr>
          <td style="text-align: center">1</td>
          <td style="text-align: center">1</td>
          <td style="text-align: center">0</td>
      </tr>
  </tbody>
</table>
<p>Following this same logic of combining gates, we can use a NAND gate and invert each switch input with a NOT. Thus, we&rsquo;ll have the following:</p>
<p><em>Interactive circ widget &mdash; <a href="https://jeffersonmourak.com/blog/logic-gates-en/">view it on the blog</a>.</em></p>
<pre><code>╭───╮     ╭───╮     ╭─────────────╮     ╭───╮
│ a ├○───▶┤NOT├○───▶┤             │ ╭──▶┤LED│
╰───╯     ╰───╯     │[nand:_nand_]├○╯   ╰───╯
                 ╭─▶┤             │          
                 │  ╰─────────────╯          
                 │                           
╭───╮     ╭───╮  │                           
│ b ├○───▶┤NOT├○─╯                           
╰───╯     ╰───╯                              </code></pre>
<p>Analyzing the diagram above, we see that when both switches are off, both signals will be inverted by the NOT, and the NAND will result in ¬∧(1, 1) = 0. So with both off, the lamp turns off. But what happens when we have ¬∧(1, 0) or ¬∧(0, 1)? To find out, let&rsquo;s analyze the truth table:</p>
<table>
  <thead>
      <tr>
          <th style="text-align: center">∨</th>
          <th style="text-align: center">0</th>
          <th style="text-align: center">1</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td style="text-align: center">0</td>
          <td style="text-align: center">0</td>
          <td style="text-align: center">1</td>
      </tr>
      <tr>
          <td style="text-align: center">1</td>
          <td style="text-align: center">1</td>
          <td style="text-align: center">1</td>
      </tr>
  </tbody>
</table>
<figure>
  <img src="https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExa2F3aTZ5Z2FhajUxem51aG5oYzBwYW1jdHI3NGswMzZzd3duMTh3biZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n9h61thJkq6Xe/giphy.gif" alt="I tawt I taw a puddy tat!" loading="lazy">
  <figcaption>I tawt I taw a puddy tat!</figcaption>
</figure><p>But wait a minute, I have the impression that I&rsquo;ve seen this table before? Yes! This is the OR logic gate we were looking for. Quite a journey, isn&rsquo;t it? Now that we know how to fix the lamp wiring, we can take a break here. This is just the first article in a series about computers. Later on, we&rsquo;ll address other logic gates and other computing concepts.</p>
<h2 id="references">References</h2>
<ul>
<li><a href="https://pt.wikipedia.org/wiki/%C3%81lgebra_booliana">Boolean algebra (Wikipedia)</a></li>
<li><a href="https://en.wikipedia.org/wiki/Boolean_algebra">Boolean Algebra (Wikipedia)</a></li>
<li><a href="https://pt.wikipedia.org/wiki/Tabela-verdade">Truth table (Wikipedia)</a></li>
<li><a href="https://www.youtube.com/watch?v=QZwneRb-zqA">Exploring How Computers Work (YouTube)</a></li>
<li><a href="https://www.youtube.com/watch?v=sTu3LwpF6XI">Making logic gates from transistors (YouTube)</a></li>
<li><a href="https://www.youtube.com/watch?v=HjneAhCy2N4">HOW TRANSISTORS RUN CODE? (YouTube)</a></li>
</ul>
]]></content:encoded></item></channel></rss>