Javascript ArrayBuffer to Hex

匿名 (未验证) 提交于 2019-12-03 02:59:02

问题:

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:

  1. Converts the buffer into an array.
  2. For each x the array, it converts that element to a hex string (e.g., 12 becomes c).
  3. Then it takes that hex string and left pads it with zeros (e.g., c becomes 0c).
  4. 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 ArrayBuffers the same way that Node dumps Buffers.

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> 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!