Hexadecimal

JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.
   define variable to = 0xFF;  <== result will be 255

By default, Javascript displays numbers as base 10 decimals. But you can use the toString() method to output numbers as base 16 (hex), base 8 (octal), or base 2 (binary).
   var myNumber = 128;
     myNumber.toString(16); 
<== returns 80 Hexadecimal
     myNumber.toString(8);  <== returns 200 Octal
     myNumber.toString(2);  <== returns 10000000 Binary

HTML file: Displayed by browser:
<body>
<h4>Numeric constants, preceded by 0x, are interpreted as hexadecimal:</h4>
<p id="demo"></p>
<hr />
<h4>The toString() method can output numbers as base 16 (hex), base 8 (octal), or base 2 (binary):</h4>
<p id="demo1"></p>
<hr />
<h4>Never write a number with a leading zero:</h4>
<p id="demo2"></p>
<script>
    document.getElementById("demo").innerHTML = "0xFF = " + 0xFF;
       // Results are in the first section
    var myNumber = 128;
    document.getElementById("demo1").innerHTML = "128 = " +
      myNumber + " Decimal, " +
      myNumber.toString(16) + " Hexadecimal, " +
      myNumber.toString(8) + " Octal, " +
      myNumber.toString(2) + " Binary."
         // Results are in the second section
    var myNumber7 = 07;
    document.getElementById("demo2").innerHTML = "07 = " +
      myNumber7 + " Decimal, " +
      myNumber7.toString(16) + " Hexadecimal, " +
      myNumber7.toString(8) + " Octal, " +
      myNumber7.toString(2) + " Binary."
         // Results are in the second section
</script>
</body>

Numeric constants, preceded by 0x, are interpreted as hexadecimal:


The toString() method can output numbers as base 16 (hex), base 8 (octal), or base 2 (binary):


Never write a number with a leading zero:


Good habit

Never write a number with a leading zero (like 07). Some JavaScript versions interpret numbers as octal if they are written with a leading zero.

Back Table of Contents Next