klren0312 / daliy_knowledge

知识积累,正确使用方式是watch
22 stars 4 forks source link

js读取文件 获取ascii 和 十六进制 #810

Open klren0312 opened 4 months ago

klren0312 commented 4 months ago
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Read Binary File from URL</title>
</head>
<body>

<button onclick="loadBinaryFile()">Load Binary File</button>

<script>
  function loadBinaryFile() {
    const fileUrl = '1.bin'
    fetch(fileUrl)
      .then(response => {
        if (!response.ok) {
          throw new Error(`Network response was not ok: ${response.status}`)
        }
        return response.arrayBuffer()
      })
      .then(binaryContent => {
        // 在这里可以对二进制内容进行处理
        displayBinaryContent(binaryContent)
      })
      .catch(error => {
        console.error('Error loading binary file:', error)
      })
  }

  function displayBinaryContent(binaryContent) {
    // 这里仅将二进制内容转为字符串进行显示,实际处理可能涉及更复杂的逻辑
    const uint8Array = new Uint8Array(binaryContent)

    // 二进制转成ascii
    const binaryString = uint8Array.reduce((acc, byte) => acc + String.fromCharCode(byte), '')
    console.log(binaryString)

    // 二进制转换为十六进制字符串
    const hexArray = Array.from(uint8Array, byte => byte.toString(16).padStart(2, '0'))
    const hexString = hexArray.join('')
    console.log(hexString)
  }
</script>

</body>
</html>