What @ILM said, and note that in reality, youβre unlikely to ever use 3 or 4 as a base.
Base 10 is decimal. Base 12 (duodecimal) has had quite a lot of weird political stuff around it since the 17th century as various people have tried to make it a standard over decimal. But we have 10 fingers, not 12, so we use decimal, so base 12 is not common.
Base 60 is common, as it is used for circular counting systems (clock time, degrees).
Base 2 is binary, so it quite useful when dealing with computers. Base 8 (octal) is used as a more compact way of expressing larger binary numbers. Base 16 (hexadecimal) is an even more compact way of expressing binary numbers and youβll have encountered it with colours (#ffffff
, #1d4c5f
, the number is the 6 hex digits after the #
) - 0 1 2 3 4 5 6 7 8 9 a b c d e f.
EDIT: It might help to have an example here
So say I want to convert a hex colour to an rgb colour, so #ffffff
is the same as rgb(255, 255, 255)
.
function hexToRgb (hex) {
/**
* This regex splits a hex string to its component parts (red, green, blue).
*
* ^ # start of string
* #? # possibly a hash character
* ([a-f\d]{2}) # two characters, either a number or a, b, c, d, e or f
* ([a-f\d]{2}) # two characters, either a number or a, b, c, d, e or f
* ([a-f\d]{2}) # two characters, either a number or a, b, c, d, e or f
* $ # end of string
*/
// `exec` will return an array, where the first element is the input,
// and the next 3 elements are the groups captured by the regex --
// i.e. the patterns in the regex surrounded by brackets.
const [_, r, g, b] = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
// Now run parseInt on each of the components, with a radix of 16:
return `rgb(${parseInt(r, 16)}, ${parseInt(g, 16)}, ${parseInt(b, 16)})`;
}
So
hexToRgb("#ffffff"); // returns "rgb(255, 255, 255)"
hexToRgb("#1d1d1d"); // returns "rgb(29, 29, 29)"
And to go the other way, you can take a number and run toString
with a radix, kinda the inverse of parseInt
:
function rgbToHex (rgbString) {
// Take a string like `rgb(255, 255, 255)` and grab the numeric values from it:
const [_, r, g, b] = /^rgb\((\d+),\s*,(\d+),\s*,(\d+)\)$/;
// The numeric values will be strings, so convert to a decimal integer,
// then convert to a base-16 numeric string:
return `#${parseInt(r, 10).toString(16)}${parseInt(r, 10).toString(16)}${parseInt(r, 10).toString(16)}`;
}
or, if you can put the individual numbers in:
function rgbToHex(r, g, b) {
return `#${r.toString(16)}${g.toString(16)}${b.toString(16)}`;
}