For example, to get the binary equivalent of 132 you can do:
(132).toString(2); //->"10000100" (32).toString(2); //->"100000"
Notice that binary is not zero filled
Random hex generator
One good use of number systems is a hexadecimal converter.
Hexadecimal (Hex for short) is base 16 so it uses 0-9 from decimal, and then "ABCDEF" for values greater than 9,
Hex is used a lot in CSS (well it was before "rgb" and "rgba", but I still use it). In css a hexadecimal colour is formed of 3 pairs of characters (or 3 characters for shorthand) each representing the colours red, green, and blue respectively.
FF0000 would be red,
00FF00 would be green.
F00 would be shorthand for red.
So lets create some random numbers.
Math.floor(Math.random() * 16)
So using this we can get some colours going on. I can sing a rainbow.
red = Math.floor(Math.random() * 16).toString(16); green = Math.floor(Math.random() * 16).toString(16); blue = Math.floor(Math.random() * 16).toString(16);
So from that we could get a colour of "#dce".
Converting back to decimal
To convert from hex (or any other number system) to an integer, you can use parseInt:
yourNumber = parseInt(hexString, 16);
- the base of the number system. Binary is radix 2, decimal is radix 10