Converting numeric bases with JavaScript

0

How to build a table with JavaScript to display decimal, binary, octal, and hexadecimal numbers.

For (var i=0;  i <=<?php echo $num ?> ; i++){
   ......................
}

document.write ....

The variable $num is obtained via a form's post

Expected result

_________________________________________
Decimal  |   Hex  |   Octal   |   Binário
   0     |    0   |     0     |      0
   1     |    1   |     1     |      1
   2     |    2   |     2     |     10

and so on.

    
asked by anonymous 11.05.2017 / 03:08

1 answer

1

The toString () method is available on all versions of all browsers and accepts a base parameter.

If we set this base parameter between 2 and 16, we can convert numbers to the equivalents in string in the different numeric bases.

var content = "" 
for (var i = 0; i <= 5 ; i++) { 
content += "<TR>" 
content += "<TD>" + i.toString(10) + "</TD>" 
content += "<TD>" + i.toString(16) + "</TD>" 
content += "<TD>" + i.toString(8) + "</TD>" 
content += "<TD>" + i.toString(2) + "</TD></TR>" 
} 
document.write("<table><th>Decimal</th><th>Hexadecimal</th><th>Octal</th><th>Binário</th></tr>"+content+"</table>")
  

You should replace in the above code for (var i = 0; i <= 5 ; i++) {

     

by For (var i=0; i <=<?php echo $num ?> ; i++){

Source: JavaScript the Bible.

    
11.05.2017 / 06:30