如何将缓冲区数组转换为hex?

当我调用其中一个API端点时,我得到一个JSON对象中的Buffer数组。 我想这个数组转换为一个更“可用”的forms(hex?),所以我可以比较它们等,这是什么对象目前看起来像:

"hash": { "type": "Buffer", "data": [ 151, 14, 51, 26, 46, 52, 5, 151, 99, 107, 38, 188, 138, 180, 76, 56, 108, 214, 135, 213, 125, 134, 105, 139, 129, 236, 206, 157, 67, 1, 12, 12 ] } 

我将如何去将这个数组转换为hex(或string等),以便我可以比较散列?

您可以创build一个新的缓冲区并将其转换为您需要的格式。

 var o = {"hash": { "type": "Buffer", "data": [ 151, 14, 51, 26, 46, 52, 5, 151, 99, 107, 38, 188, 138, 180, 76, 56, 108, 214, 135, 213, 125, 134, 105, 139, 129, 236, 206, 157, 67, 1, 12, 12 ] } } console.log(new Buffer(o.hash,'hex').toString('hex')); // 970e331a2e340597636b26bc8ab44c386cd687d57d86698b81ecce9d43010c0c 

使用Number.prototype.toString

 var json = '{"hash": {"type": "Buffer","data": [151,14,51]}}'; var parsed = JSON.parse(json); document.write("data: " + JSON.stringify(parsed.hash.data) + "<br>"); document.write("hex: "); parsed.hash.data.forEach(function(b) { document.write(("00" + b.toString(16)).substr(-2)); });