<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Hex Encode and Decode</title>
</head>

<body>
  <h1>Hex Encode and Decode</h1>

  <input type="text" id="input-box" placeholder="Enter text to encode or decode">
  <button id="encode-button" onclick="encode()">Encode</button>
  <button id="decode-button" onclick="decode()">Decode</button>
  <br>
  <textarea id="output-box" rows="5" placeholder="Result"></textarea>

  <script>
    const inputBox = document.getElementById('input-box');
    const encodeButton = document.getElementById('encode-button');
    const decodeButton = document.getElementById('decode-button');
    const outputBox = document.getElementById('output-box');

    // 十六进制编码函数
    function hexEncode(str) {
      let hexStr = '';
      for (let i = 0; i < str.length; i++) {
        const hex = str.charCodeAt(i).toString(16);
        hexStr += ('000' + hex).slice(-4); // 每个字符为16位,不足则在前面补0
      }
      return hexStr;
    }

    // 十六进制解码函数
    function hexDecode(hexStr) {
      let decodedStr = '';
      for (let i = 0; i < hexStr.length; i += 4) {
        const hex = hexStr.substr(i, 4);
        const dec = parseInt(hex, 16);
        decodedStr += String.fromCharCode(dec);
      }
      return decodedStr;
    }

    // 点击编码按钮时进行编码
    function encode() {
      const inputStr = inputBox.value;
      const encodedStr = hexEncode(inputStr);
      outputBox.value = encodedStr;
    }

    // 点击解码按钮时进行解码
    function decode() {
      const inputStr = inputBox.value;
      const decodedStr = hexDecode(inputStr);
      outputBox.value = decodedStr;
    }
  </script>
</body>

</html>