I am using node.js v4.5. Suppose I have this Uint8Array variable.
我正在使用node.js v4.5。假设我有这个Uint8Array变量。
var uint8 = new Uint8Array(4);
uint8[0] = 0x1f;
uint8[1] = 0x2f;
uint8[2] = 0x3f;
uint8[3] = 0x4f;
This array can be of any length but let's assume the length is 4.
这个数组可以是任何长度,但我们假设长度是4。
I would like to have a function that that converts uint8
into the hex string equivalent.
我想有一个函数,将uint8转换为十六进制字符串等效。
var hex_string = convertUint8_to_hexStr(uint8);
//hex_string becomes "1f2f3f4f"
2 个解决方案
#1
15
You can use Buffer.from()
and subsequently use toString('hex')
:
您可以使用Buffer.from()并随后使用toString('hex'):
let hex = Buffer.from(uint8).toString('hex');
#2
3
Another solution: reduce
:
另一解决方案:减少:
uint8.reduce(function(memo, i) {
return memo + ('0' + i.toString(16)).slice(-2); //padd with leading 0 if <16
}, '');
Or map
and join
:
或者地图和加入:
uint8.map(function(i) {
return ('0' + i.toString(16)).slice(-2);
}).join('');
#1
15
You can use Buffer.from()
and subsequently use toString('hex')
:
您可以使用Buffer.from()并随后使用toString('hex'):
let hex = Buffer.from(uint8).toString('hex');
#2
3
Another solution: reduce
:
另一解决方案:减少:
uint8.reduce(function(memo, i) {
return memo + ('0' + i.toString(16)).slice(-2); //padd with leading 0 if <16
}, '');
Or map
and join
:
或者地图和加入:
uint8.map(function(i) {
return ('0' + i.toString(16)).slice(-2);
}).join('');