Sikau

How computers work · Day 5 · about 35 min

Project: Number inspector

Read number literals in any base and describe a byte every way at once.

A tool for the rest of the course

Build the little tool you'll want while debugging bits: type 0x2A, 0b101010, 42 or -5 and get a number; give it a byte and see it as binary, hex, unsigned, signed and as a character — all at once.

Parsing literals carefully

Building it also rehearses every conversion from this unit, which is the best way to make them stick.

A parser should accept exactly what it promises and reject everything else with a clear error. Trim spaces, peel off an optional minus sign, then look at the prefix: 0b means binary, 0x hex, otherwise decimal. Check every remaining character belongs to that base before converting, so 0b102 or 0xG1 fail loudly instead of returning a wrong number.

function parseLiteral(text) {
  let s = text.trim();
  const negative = s.startsWith("-");
  if (negative) s = s.slice(1);
  let base = 10, digits = s;
  if (/^0b/i.test(s)) { base = 2; digits = s.slice(2); }
  else if (/^0x/i.test(s)) { base = 16; digits = s.slice(2); }
  const valid = { 2: /^[01]+$/, 10: /^[0-9]+$/, 16: /^[0-9a-f]+$/i }[base];
  if (!valid.test(digits)) throw new RangeError(`Not a number: ${text}`);
  const n = [...digits.toLowerCase()].reduce((acc, d) => acc * base + parseInt(d, 16), 0);
  return negative ? -n : n;
}

The rest of this lesson

  • One byte, many viewsexplain
  • A tool you'll reuseexplain
  • Views of 0xFFmatch
  • Parse itpredict
  • The inspectorchallenge
  • Badge quizquiz
  • Unit 1 completerecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 13 lessons of How computers work