可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I've got a Javascript ArrayBuffer that I would like to be converted into a hex string.
Anyone knows of a function that I can call or a pre written function already out there?
I have only been able to find arraybuffer to string functions, but I want the hexdump of the array buffer instead.
回答1:
function buf2hex(buffer) { // buffer is an ArrayBuffer return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join(''); } // EXAMPLE: const buffer = new Uint8Array([ 4, 8, 12, 16 ]).buffer; console.log(buf2hex(buffer)); // = 04080c10
This function works in four steps:
- Converts the buffer into an array.
- For each
x
the array, it converts that element to a hex string (e.g., 12
becomes c
). - Then it takes that hex string and left pads it with zeros (e.g.,
c
becomes 0c
). - Finally, it takes all of the hex values and joins them into a single string.
Below is another longer implementation that is a little easier to understand, but essentially does the same thing:
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
回答2:
I use this to hexdump ArrayBuffer
s the same way that Node dumps Buffer
s.
function pad(n: string, width: number, z = '0') { return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n; } function hexdump(buf: ArrayBuffer) { let view = new Uint8Array(buf); let hex = Array.from(view).map(v => this.pad(v.toString(16), 2)); return `<Buffer ${hex.join(" ")}>`; }
Example (with transpiled js version):
const buffer = new Uint8Array([ 4, 8, 12, 16 ]).buffer; console.log(hexdump(buffer)); // <Buffer 04 08 0c 10>