格式 | 描述 | 用途 | 示例 |
---|---|---|---|
ArrayBuffer | 固定長度的二進(jìn)制數(shù)據(jù)緩沖區(qū),不直接操作具體的數(shù)據(jù),而是通過類型數(shù)組或DataView對象來讀寫 | 用于存儲(chǔ)和處理大量的二進(jìn)制數(shù)據(jù),如文件、圖像等 | let buffer = new ArrayBuffer(16); |
TypedArray | 基于ArrayBuffer對象的視圖,提供特定格式的讀寫接口 | 用于操作具有特定數(shù)據(jù)類型的二進(jìn)制數(shù)據(jù) | let int32View = new Int32Array(buffer); |
DataView | 提供對ArrayBuffer的復(fù)雜和靈活讀寫操作,可以讀寫任意位置的任意類型的數(shù)據(jù) | 當(dāng)需要精確控制二進(jìn)制數(shù)據(jù)的讀寫位置和格式時(shí)使用 | let dataView = new DataView(buffer); |
Blob | 表示不可變的原始數(shù)據(jù),通常是二進(jìn)制數(shù)據(jù)或文本數(shù)據(jù) | 用于處理文件、圖片等二進(jìn)制數(shù)據(jù),可以通過URL.createObjectURL()創(chuàng)建對象URL | let blob = new Blob([arrayBuffer], {type: 'image/jpeg'}); |
File | 繼承自Blob,表示用戶系統(tǒng)上的具體文件 | 用于處理用戶上傳的文件,可以獲取文件名、大小等信息 | let file = new File([blob], 'filename.jpg', {type: 'image/jpeg'}); |
Uint8Array | 8位無符號整數(shù)類型數(shù)組,用于存儲(chǔ)0到255之間的整數(shù) | 用于處理8位圖像數(shù)據(jù)、字節(jié)流等 | let uint8Array = new Uint8Array(buffer); |
Uint16Array | 16位無符號整數(shù)類型數(shù)組,用于存儲(chǔ)0到65535之間的整數(shù) | 用于處理音頻數(shù)據(jù)、圖像數(shù)據(jù)等 | let uint16Array = new Uint16Array(buffer); |
Float32Array | 32位浮點(diǎn)數(shù)類型數(shù)組,用于存儲(chǔ)浮點(diǎn)數(shù) | 用于處理浮點(diǎn)數(shù)的二進(jìn)制數(shù)據(jù),如科學(xué)計(jì)算、物理模擬等 | let float32Array = new Float32Array(buffer); |
部分使用示例:
?文章來源地址http://www.zghlxwxcb.cn/news/detail-847603.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>二進(jìn)制格式轉(zhuǎn)換示例</title>
</head>
<body>
<input type="file" id="fileInput" accept="*" />
<button onclick="convertFileToBinaryFormats()">轉(zhuǎn)換文件為二進(jìn)制格式</button>
<pre id="output"></pre>
<script>
function convertFileToBinaryFormats() {
const fileInput = document.getElementById("fileInput");
const file = fileInput.files[0];
if (!file) {
alert("未選擇文件");
return;
}
let reader = new FileReader(); // 使用let而不是const
reader.onload = function (event) {
const arrayBuffer = event.target.result;
// ArrayBuffer
console.log("ArrayBuffer:", arrayBuffer);
// TypedArray (例如 Uint8Array)
const uint8Array = new Uint8Array(arrayBuffer);
console.log("Uint8Array:", uint8Array);
// DataView
const dataView = new DataView(arrayBuffer);
console.log("DataView:", dataView);
// Blob
const blob = new Blob([arrayBuffer], { type: file.type });
console.log("Blob:", blob);
// 顯示部分Uint8Array內(nèi)容作為示例
const output = `文件類型: ${file.type}<br>`;
output += `ArrayBuffer長度: ${arrayBuffer.byteLength} 字節(jié)<br>`;
output += `Uint8Array前10個(gè)字節(jié): ${Array.from(uint8Array.slice(0, 10))
.map((b) => b.toString(16).padStart(2, "0"))
.join(" ")}<br>`;
document.getElementById("output").textContent = output;
};
reader.readAsArrayBuffer(file);
}
</script>
</body>
</html>
文章來源:http://www.zghlxwxcb.cn/news/detail-847603.html
到了這里,關(guān)于JS中的常見二進(jìn)制數(shù)據(jù)格式的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!