Javascript ArrayBuffer到Hex [英] Javascript ArrayBuffer to Hex
本文介绍了Javascript ArrayBuffer到Hex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Javascript ArrayBuffer,我希望将其转换为十六进制字符串。
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?
我只能找到arraybuffer到字符串函数,但我想要数组缓冲区的hexdump。
I have only been able to find arraybuffer to string functions, but I want the hexdump of the array buffer instead.
推荐答案
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
此功能分为四个步骤:
- 将缓冲区转换为数组。
- 对于每个
x
数组,它将该元素转换为十六进制字符串(例如,12
变为c
)。 / li>
- 然后它需要那个十六进制字符串并用零填充它(例如,
c
变为0c
)。 - 最后,它获取所有十六进制值并将它们连接成一个字符串。
- Converts the buffer into an array.
- For each
x
the array, it converts that element to a hex string (e.g.,12
becomesc
). - Then it takes that hex string and left pads it with zeros (e.g.,
c
becomes0c
). - 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
这篇关于Javascript ArrayBuffer到Hex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文