Search code examples
javascripthexrgb

Why does .toString(16) convert rgb, decimal, or other inputs into a hexidecimal


I've tried searching everywhere I could to find the answer as to why .toString(16) converts a number to a hexidecimal value. My first question is, why 16? My second question is, how can this return letters even though I see no letters going into the code. For example, I don't understand how the following code returns ff instead of a number.

var r = 255;
r.toString(16); //returns ff

If anyone has any links or insights as to why this is, please let me know. I'm very curious. Thank you in advance!


Solution

  • Hexadecimal is base 16. Break down the words: hexa, meaning 6; decimal, meaning 10. 10 + 6 = 16. A few major bases are:

    • Base 2: Binary, 2 numbers: [0, 1]
    • Base 8: Octal, 8 numbers: [0, 7]
    • Base 10: Decimal, 10 numbers: [0, 9]
    • Base 16: Hexadecimal, 16 symbols: [0, 9] and [A, F]

    Per the MDN documentation:

    For Number objects, the toString() method returns a string representation of the object in the specified radix.

    Parameters

    radix: Optional. An integer between 2 and 36 specifying the base to use for representing numeric values.

    This means it converts the number into a string, and based on the radix. The syntax for Number.prototype.toString is:

    number.toString([radix])
    

    Where radix is optional. If you specify the radix, it will convert with that base, so 16 is hexadecimal. If radix is not specified, 10 (decimal) is assumed. Here's a snippet:

    var num = 16;
    
    console.log(num.toString()) //"16", base 10 is assumed here if no radix given
    console.log(num.toString(16)) //"10", base 16 is given

    Now, regarding RGB values: take (255, 255, 255) [white] as an example. Each individual value (red, green, or blue) is represented in hex. Since 255 is 0xFF or simply FF in hex, the full representation is FFFFFF, or ffffff you see.