如何将一个hexstring转换为一个字节和一个字节在Javascript中的hexstring?

如何将string中表示的hex代码转换为一个字节,并在Javascript中反转?

var conv = require('binstring'); var hexstring ='80'; var bytestring = conv(hexstring, {in:'hex', out:'utf8'}); var backtohexstring = conv(bytestring, {in:'utf8', out:'hex'}); // != '80'??? 

backtohexstring解码传入的数据string到正确的hex(我也使用utf8与字节,因为它看起来像打印到控制台时传入的string),所以我很困惑…

我还发现这两个原生的JavaScript函数,解码器工作在我的传入stream,但我仍然无法得到hex编码…

 function encode_utf8( s ) { return unescape( encodeURIComponent( s ) ); } function decode_utf8( s ) { return decodeURIComponent( escape( s ) ); } 

下面是一个node.js特定的方法,利用节点标准lib提供的Buffer类。

https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings

要获取字节(0-255)值:

 Buffer.from('80', 'hex')[0]; // outputs 128 

并转换回来:

 Buffer.from([128]).toString('hex'); // outputs '80' 

要转换为utf8:

 Buffer.from('80', 'hex').toString('utf8'); 

你可以使用Number.prototype.toString和parseInt 。

关键是要利用radix参数为你做转换。

 var bytestring = Number('0x' + hexstring).toString(10); // '128' parseInt(bytestring, 2).toString(16); // '80'