본문 바로가기

JavaScript/javascript 기초 공부하기

자바스크립트 10진법 2, 8, 16진법으로 변환하기

 

<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <div><span>10진수 </span><input type="text" id="inputValue"> <button onclick="onClick()">button</button></div>
  <div><span>2진수 </span><span id="two">값</span></div>
  <div><span>8진수 </span><span id="oct">값</span></div>
  <div><span>16진수 </span><span id="hex">값</span></div>
  <script>
    /*
    var number = 12;

      // 10진수 -> 2 진수, 8 진수, 16 진수
      //document.getElementById("demo").innerHTML =
      /*
        "10진수: " + number + "<br>" +
        "2진수: " + number.toString(2) + "<br>" +
        "8진수: " + number.toString(8) + "<br>" +
        "16진수: " + number.toString(16) + "<br>";
        */
    // 2진수, 8진수, 16진수 -> 10진수
    //   var bin = "11001010";
    //   var oct = "24";
    //  var hex = "ab";
    //   document.getElementById("demo").innerHTML =
    //    "2진수: " + bin + " 10진수: " + parseInt(bin, 2) + "<br>" +
    //   "8진수: " + oct + " 10진수: " + parseInt(oct, 8) + "<br>" +
    //  "16진수: " + hex + " 10진수: " + parseInt(hex, 16) + "<br>";
    //
    function onClick() {
      var input = document.getElementById("inputValue").value;
      console.log(input);
      document.getElementById("two").innerHTML = parseInt(input).toString(2);
      document.getElementById("oct").innerHTML = parseInt(input).toString(8);
      document.getElementById("hex").innerHTML = parseInt(input).toString(16);

    }
  </script>
</body>

</html>