Javascript - Chuyển đổi một số nhị phân thành một số thập phân

Viết một hàm JavaScript để chuyển một số nhị phân thành một số thập phân.

Test Data: console.log(bin_to_dec('110011')); console.log(bin_to_dec('100')); 51 4

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

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Binary number to a decimal number</title>
  <script>
  function bin_to_dec(bstr) { 
    return parseInt((bstr + '')
    .replace(/[^01]/gi, ''), 2);
}
document.write(bin_to_dec('110011')+"<br/>");
document.write(bin_to_dec('100')+"<br/>");
   </script>
</head>
<body>

</body>
</html>

Xem ví dụ

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

Flowchart: JavaScript Math- Convert a binary number  to a decimal 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").