So i have an object, type "Buffer", data is array of [0,0,2,6,116].
If treat this array as decimals, i want to convert into hex string. 0, 0, 2, 6, 116 => 0, 0, 2, 6, 74 => 00, 00, 02, 06, 74
Eventually i want to see 20674 or 0000020674 in the webpage.
What's the fastest way/build-in function in Javascript please ?
String concatenation might be expensive depending of the size of your buffer. So the quickest way is probably to encode the data and use String.fromCharCode
to build the string :
function dataToString(data){
var buffer = [], table = [48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70];
for (var i = 0; i < data.length; ++i){
buffer.push(table[data[i] >> 4]);
buffer.push(table[data[i] & 15]);
}
return String.fromCharCode.apply(String, buffer);
}
dataToString([0,0,2,6,116]);
Or with string concatenation:
[0,0,2,6,116].map(v => "0123456789ABCDEF"[v >> 4] + "0123456789ABCDEF"[v & 15]).join('');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.