Trang chủ / Javascript / Chuyển đổi số thập phân thành số nhị phân, thập lục phân hoặc bát phân

Chuyển đổi số thập phân thành số nhị phân, thập lục phân hoặc bát phân

Ví dụ:

JavaScript: Math - Convert a decimal number to binary number.

JavaScript: Math - Convert a decimal number to hexadecimal number

JavaScript: Math - Convert a decimal number to octal number

Mã nguồn:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Convert a decimal number to binary, hexadecimal or octal number</title>
  <script>
   dec_to_bho  = function(n, base) { 
    if (n < 0) {
      n = 0xFFFFFFFF + n + 1;
     } 
	switch (base)  
	{  
	case 'B':  
	return parseInt(n, 10).toString(2);
	break;  
	case 'H':  
	return parseInt(n, 10).toString(16);
	break;  
	case 'O':  
	return parseInt(n, 10).toString(8);
	break;  
	default:  
	return("Wrong input.........");  
	}  
	}

	document.write(dec_to_bho(120,'B')+"<br/>");
	document.write(dec_to_bho(120,'H')+"<br/>");
	document.write(dec_to_bho(120,'O')+"<br/>");
   </script>
</head>
<body>

</body>
</html>

Xem ví dụ

 

Lưu đồ thuật toán:

Flowchart: JavaScript Math- Convert a decimal number to binary, hexadecimal or octal number

 

 

 

Thấy bài viết hữu ích?

Ủng hộ tác giả để có thêm nhiều bài viết chất lượng nhé!

Tư vấn lộ trình CNTT 🤖