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
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>
Lưu đồ thuật toán: