Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created May 1, 2016 19:43
Show Gist options
  • Save tmcw/187507abb500b3ca61719a687f1ce551 to your computer and use it in GitHub Desktop.
Save tmcw/187507abb500b3ca61719a687f1ce551 to your computer and use it in GitHub Desktop.
layout title categories published
post
Numbers
blog
true

Computers don't know our numbers, but all they know is numbers.

0
<script> (function() { var bit = document.getElementById('bit'); window.setInterval(function() { bit.innerHTML = bit.innerHTML === '0' ? '1' : '0'; }, 2000); })(); </script>

Or they know bits. Just 1 or 0, on or off, bits are the smallest possible data: yes or no. The two states are the bi in binary, the reason why computers prefer powers of two.

<script> (function() { var integer = document.getElementById('integer'); var thisint = 0, dir = 1; function pad4(_) { while(_.length < 4) { _ = '0' + _; } return _; } window.setInterval(incint, 1000); function incint() { integer.innerHTML = pad4('' + thisint.toString(2)) + ' = ' + thisint; thisint += dir if (thisint === 15 || thisint === 0) dir = -dir; } incint(); })(); </script>

Whole numbers are made up of bits lined up, and given numbers. The one to the furthest right is 1, the next 2, the next 4, and 8, and so on. If the second bit from the right is flipped, add 2.

<script> (function() { var negativeinteger = document.getElementById('negative-integer'); var thisint = -15, dir = 1; function pad5n(i) { var _ = i.toString(2).replace('-', ''); while(_.length < 4) { _ = ((i > 0) ? '0' : '1') + _; } if (i < 0) { var bits = _.split('').map(function(s) { return s == '0' ? '1' : '0'; }); var add = 3, carry = false; do { if (bits[add] == '1') carry = true; else carry = false; bits[add] = '1'; add--; } while (carry); return bits.join(''); } return _; } window.setInterval(incint, 1000); function incint() { negativeinteger.innerHTML = pad5n(thisint) + ' = ' + thisint; thisint += dir if (thisint === 15 || thisint === -15) dir = -dir; } incint(); })(); </script>

Negative numbers add another trick: two's complement makes it possible to represent all negative numbers in a way that doesn't give you both +0 and -0 and is really easy for computers to compute in hardware.

Letters come out of numbers. Originally just the numbers from zero to 255, and you would have to choose what language those represented off the bat. But UTF8 made it possible to stretch numbers beyond that range and use any language you want, in combination with any other language.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment