Binary, octal and hex literals in JavaScript
Beginner · 4 min read
Most numbers in code are written in base 10, like 255. But some values are easier to read in another base. A color like #1e09ff is written in hexadecimal. File permissions on Linux, like 755, are octal. Bit masks, which switch individual bits on or off, are clearest in binary. JavaScript lets you type numbers directly in all three, using a short prefix at the front.
In this tutorial you will write 255 in binary, octal and hex, check they are the same number, and then build a hex color from three channel values, padding each one so the color comes out right. You need to know what a string is and how map and join work.
The three prefixes
0bmeans binary (base 2): digits 0 and 1.0omeans octal (base 8): digits 0 to 7.0xmeans hexadecimal (base 16): digits 0 to 9, then a to f.
console.log(0b11111111, 0o377, 0xff); // 255 255 255
All three print 255. A prefix is only a way of writing the number in your code. Once JavaScript has read it, 0xff and 255 are exactly the same value. console.log always shows numbers in base 10.
Separators for long numbers
You can put underscores between digits to make long numbers easier to read. JavaScript ignores them:
console.log(0b1010_1010, 1_000_000); // 170 1000000
console.log(1_000_000 === 1e6); // true
An underscore must sit between two digits. A trailing underscore (1_) or a doubled one (1__000) is a syntax error, and a leading one (_1000) is not a number at all: JavaScript reads it as a variable name.
Here is the exercise. Try it on your own first if you like, then read on and we will build it together.
67 Binary, octal and hex literals, and padding the output
easyWrite 255 as a binary, an octal and a hex literal, and confirm they are all the same number. Then build a hex colour from the channels 30, 9 and 255, padding each to two characters.
Stuck? Three hints, smallest first
- 1. The prefixes are
0b,0oand0x, and underscores may be used as separators. - 2.
(10).toString(16)is one character, sopadStart(2, "0")is not optional. - 3.
padStartpads up to a minimum length and never truncates.
Step 1: how a hex color works
A color like #1e09ff is three pairs of hex digits: red, green and blue, each from 00 (0) to ff (255). Our channels are red 30, green 9 and blue 255. Going the other way, from a number to hex, uses toString(16):
console.log((30).toString(16), (9).toString(16), (255).toString(16)); // 1e 9 ff
Notice the 9. It gives a single character, 9, not the two characters 09.
Step 2: the wrong turn, joining without padding
const channels = [30, 9, 255];
const unpadded = '#' + channels.map((c) => c.toString(16)).join('');
console.log(unpadded, unpadded.length); // #1e9ff 6
This looks almost right, but it has five hex digits instead of six. A browser reading #1e9ff can't know that the 9 was meant to be green. The color is wrong, and the bug only appears when a channel is below 16, so it can hide for a long time.
Step 3: pad each channel to two characters
padStart(length, fill) adds fill characters to the front of a string until it reaches length:
const hex = (c) => c.toString(16).padStart(2, '0');
const colour = '#' + channels.map(hex).join('');
console.log(hex(9), hex(30)); // 09 1e
console.log(colour); // #1e09ff
'9' becomes '09', and '1e' is already two characters, so it stays as it is. Now every channel is exactly two characters and the color is correct. (The answer's variable is spelled colour.)
Step 4: uppercase if you want it
toString(16) always gives lowercase letters. Browsers accept either case, so uppercase is only about looks:
console.log(colour.toUpperCase()); // #1E09FF
Step 5: bytes in binary
The same padding trick makes binary easy to read. A byte is 8 bits, so pad to 8:
const byteBits = (n) => n.toString(2).padStart(8, '0');
console.log([5, 64, 255].map(byteBits)); // [ '00000101', '01000000', '11111111' ]
Now 5 reads as a full byte, 00000101, and you can see straight away which bits are on.
Step 6: padStart never cuts
padStart pads up to a minimum length. If the string is already longer, it is left alone:
console.log(byteBits(511), byteBits(511).length); // 111111111 9
511 needs nine bits, so you get nine characters, not eight. If your code assumes every result is one byte, it will be wrong for anything above 255, and nothing warns you. Check the range yourself if it matters.
Step 7: a leading zero in a string
In code, an octal number needs the 0o prefix. In a string, a leading zero means nothing special:
console.log(Number('010')); // 10
console.log(parseInt('010', 8)); // 8
Number('010') is plain decimal 10. You only get octal when you ask for base 8 yourself.
The full solution
The answer panel prints the three literals, the separators, the padded and unpadded colors, the uppercase color, three bytes in binary, the leading-zero string, and the nine-bit value. Press Run to see the output.
const channels = [30, 9, 255];
const hex = (c) => c.toString(16).padStart(2, '0');
const colour = '#' + channels.map(hex).join('');
const unpadded = '#' + channels.map((c) => c.toString(16)).join('');
const byteBits = (n) => n.toString(2).padStart(8, '0');
console.log('0b11111111, 0o377, 0xff:', 0b11111111, 0o377, 0xff);
console.log('separators :', 0b1010_1010, 1_000_000);
console.log('colour :', colour);
console.log('unpadded :', unpadded, '<- five digits, a different colour');
console.log('uppercase :', colour.toUpperCase());
console.log('bytes :', [5, 64, 255].map(byteBits));
console.log("Number('010') :", Number('010'), "and parseInt('010', 8) is", parseInt('010', 8));
console.log('nine bits in an 8-pad :', byteBits(511), byteBits(511).length);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('all three literals are the number 255', [0b11111111, 0o377, 0xff], [255, 255, 255]);
test('and underscores are allowed anywhere between digits', [0b1010_1010, 1_000_000 === 1e6], [170, true]);
test('30, 9, 255 padded is the colour #1e09ff', colour, '#1e09ff');
test('unpadded, the 9 takes one character and the whole string is a digit short', [unpadded, unpadded.length], ['#1e9ff', 6]);
test('hex digits come out lowercase, so uppercase them yourself', [(255).toString(16), colour.toUpperCase()], ['ff', '#1E09FF']);
test('padStart to 8 gives a readable byte', [byteBits(5), byteBits(255)], ['00000101', '11111111']);
test('but it pads to a minimum and never truncates', [byteBits(511), byteBits(511).length], ['111111111', 9]);
test('a leading zero is decimal to Number, and octal only if you say so', [Number('010'), parseInt('010', 8)], [10, 8]);
The prefixes are notation, nothing more: 0xff and 255 are the same double, and toString(radix) is how you get back the other way. Numeric separators (0b1010_1010, 1_000_000) are permitted between digits and make masks and large constants readable; they are not allowed leading, trailing or doubled.
padStart is where colour code goes wrong. (30).toString(16) is '1e' but (9).toString(16) is '9', so joining unpadded channels produces a five-digit string that the browser parses as some other colour entirely — a bug that only appears once a channel drops below 16. Pad every channel. And note the second half of that assertion: padStart is a minimum, so a value that does not fit comes out longer, which is a silent overflow if you were assuming eight bits.
Common mistakes
- Not padding the channels. Any channel below 16 gives one hex digit, and the color string comes out a digit short.
- Thinking a prefix changes the number.
0xffand255are the same value. The prefix only changes how you write it in code. - Expecting
padStartto shorten a string. It only ever adds characters. A value that doesn't fit comes out longer.
Try it yourself
- Write
rgbToHex(r, g, b)that returns a color string, and test it withrgbToHex(0, 0, 0). You should get#000000. - Go the other way: split
'#1e09ff'into pairs and turn each back into a number withparseInt(pair, 16). - Write the Linux permission
755as an octal literal, and print it in base 10 and in binary.