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

 

 

 



Chatbot Tư vấn Lộ trình CNTT 🤖
Chào bạn! Tôi có thể tư vấn về các lộ trình học CNTT dựa trên roadmap.w3typing.com. Hãy chọn một từ khóa dưới đây hoặc gõ câu hỏi của bạn (ví dụ: "Frontend", "Backend", "Python", "DevOps").