Javascript ArrayBuffer があり、これを 16 進文字列に変換したいと考えています。
呼び出すことができる関数、または既に作成されている関数を知っている人はいますか?
配列バッファから文字列への関数しか見つけられませんでしたが、代わりに配列バッファの 16 進ダンプが必要です。
ベストアンサー1
function buf2hex(buffer) { // buffer is an ArrayBuffer
return [...new Uint8Array(buffer)]
.map(x => x.toString(16).padStart(2, '0'))
.join('');
}
// EXAMPLE:
const buffer = new Uint8Array([ 4, 8, 12, 16 ]).buffer;
console.log(buf2hex(buffer)); // = 04080c10
この機能は次の 4 つのステップで動作します。
- バッファを配列に変換します。
x
配列ごとに、その要素を 16 進文字列に変換します (例:12
は になりますc
)。- 次に、その 16 進文字列の左側にゼロを埋め込みます (たとえば、
c
になります0c
)。 - 最後に、すべての 16 進値を取得して 1 つの文字列に結合します。
以下は、もう少し理解しやすい、もう 1 つの長い実装ですが、基本的には同じことを行います。
function buf2hex(buffer) { // buffer is an ArrayBuffer
// create a byte array (Uint8Array) that we can use to read the array buffer
const byteArray = new Uint8Array(buffer);
// for each element, we want to get its two-digit hexadecimal representation
const hexParts = [];
for(let i = 0; i < byteArray.length; i++) {
// convert value to hexadecimal
const hex = byteArray[i].toString(16);
// pad with zeros to length 2
const paddedHex = ('00' + hex).slice(-2);
// push to array
hexParts.push(paddedHex);
}
// join all the hex values of the elements into a single string
return hexParts.join('');
}
// EXAMPLE:
const buffer = new Uint8Array([ 4, 8, 12, 16 ]).buffer;
console.log(buf2hex(buffer)); // = 04080c10