Prodotti da non perdere

In this lesson we will learn how to make a decimal to binary conversion in JavaScript.

Try the converter below, write the number and then the conversion will automatically appear in the various systems.




Furthermore, we will convert the decimal number into binary, octal and hexadecimal.

Decimal to Binary conversion online

Let’s proceed with the implementation of the various functions necessary to carry out the conversion.

First of all we develop the dec_bin function which deals with converting from decimal to binary, considering the remainder of division by 2. The function returns the binary number thus converted.

Then we develop the dec_ott function which deals with converting from decimal to octal, considering the remainder of division by 8. The function returns the octal number thus converted.

Then we implement the dec_esa function which takes care of converting from decimal to hexadecimal, considering the remainder of division by 16. If the remainder is greater than 9, the corresponding letter is taken from the array. The function then returns the converted hexadecimal number.

Finally we insert the change function which activates the automatic change when we insert the value in the decimal field.

So here is the complete JavaScript code for the binary decimal converter:

function dec_bin(num){
	binary = "";

	while(num!=0) {
		r = num % 2; 
		num = (num-r)/2; 
		binary = r + binary;
	return binary;

function dec_ott(num){ 
	octal = "";

	while(num!=0) {
		r = num % 8; 
		num = (num - r)/8;
		octal = r + octal;
	return octal;

function dec_esa(num){
	exa = ""; 
	while(num != 0) { 
		r = num % 16; 
		num = (num - r)/16; 
		ar = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
		if (r > 9) 
			r = ar[r]; 
		exa = r + exa ;
	return exa ;

function change(name) {
		n = document.getElementById("decimale").value;
                result = dec_bin(n);
		result2 = dec_ott(n);
		result3 = dec_esa(n);

In the field, where I insert the decimal number as input, I add the onkeyup event. This causes the other fields to update automatically by calling the change function developed in JavaScript.


Clearly this is just a simple way to implement a binary decimal converter, which also allows you to convert to octal and hexadecimal. Feel free to propose your solution in the comments below.

Alcuni link utili

Indice argomenti tutorial JavaScript

Template responsive con html

Come creare un css responsive

Come trovare immagini per il sito web

Quali colori scegliere per un sito web

Quali font scegliere per un sito web

PDF da un form con JavaScript