User Tools

Site Tools


λ Binary to decimal

======= Algorithm ======= <syntax js> // Converts a string of binary digits, eg. "100101", to a decimal number. function bin2dec(binary) { var decimal = 0; for (var i=0; i<binary.length; i++) { if (binary[i] === '1') { decimal = decimal * 2 + 1; } else if (binary[i] === '0') { decimal = decimal * 2; } else { // Stop parsing decimal if a non 0/1 character seen. break; } } return decimal; } </syntax> ======= Support ======= <syntax js> function run(args) { result = bin2dec(args.n); } </syntax> ======= Tests ======= <syntax js> function testA() { assert( bin2dec("100101") === 37); } function testB() { assert( bin2dec("000111100110") === 486); }</syntax> ======= Options ======= <syntax js> { "title": "Binary to decimal", "height":"300px" } </syntax> ======= Visualisation ======= <syntax html> <html> <head> <style type="text/css"> input {width:100px;} body {font-family:monospace} #start {color:blue; text-decoration:underline} </style> <script type="text/javascript"> function globals() { return { result: undefined }; } function update(n, x) { var element = document.getElementById("result"); var decimal = x.lookupInScope("decimal"); var i = x.lookupInScope("i"); var binary = x.lookupInScope("binary"); var result = x.lookupInScope("result"); element.innerHTML = ""; if (!binary) { binary = document.getElementById('n').value; } if (typeof i !== "undefined") { element.innerHTML += "<span id=start>"+binary.slice(0, i+1) + "</span>" + binary.slice(i+1) +"<br>"; } else if (typeof result !== "undefined") { element.innerHTML += "<span id=start>"+binary+"</span><br>"; } else { element.innerHTML += binary+"<br>"; } if (result) { element.innerHTML += "= "+result; } else if (!decimal) { element.innerHTML += "= 0"; } else { element.innerHTML += "= "+decimal; } } function args() { var n = document.getElementById('n').value; return {n:n}; } function change() { reset(); } </script> </head> <body> bin2dec("<input id="n" value="101010" onchange="change()">") <div id="result"></div> </body> </html> </syntax>

algorithm/binary_to_decimal.txt · Last modified: 2015/02/02 08:28 (external edit)