真是方便呀~
var val = parseInt("11111111", 2); //將 "11111111" 以2為基數剖析 , val = 255
var.toString(16); //將 val 換成16進位表示的字串
有了這兩個方法就可以簡單的完成二進位轉十六進位的程式囉
以下是我試寫的程式碼範例
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>二進位轉十六進位</title> <script> function convert(){ var source = document.getElementById("source"); var target = document.getElementById("target"); var arr = source.value.split("\n"); target.value = ""; for (var i in arr ) { var binval = parseInt(arr[i], 2); if(!isNaN(binval)) target.value += "0x" + binval.toString(16).toUpperCase() + "\n"; else target.value += "\n"; } } document.onkeyup = convert; </script> </head> <body > <h2>二進位轉十六進位</h2> <div style="width:50%; float:left;"> <span style="font-size: 20px;">二進位</span> <textarea id="source" style="width:100%; height:400px;"></textarea> </div> <div style="width:50%; float:left;"> <span style="font-size: 20px;">十六進位</span> <textarea id="target" style="width:100%; height:400px;"></textarea> </div> <div style="text-align:center;"> <button onclick="convert()" >轉換</button> </div> </body>