How do you convert a hex code represented in a string to a byte and the reverse in Javascript?
如何将字符串中表示的十六进制代码转换为字节,并在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 decodes an incoming data string to the correct hex (I also used utf8 vs. byte, because it 'looked' like the incoming string when printed to the console), so I'm confused...
backtohexstring将传入的数据字符串解码为正确的十六进制(我也使用了utf8与字节,因为它看起来像打印到控制台时的传入字符串),所以我很困惑......
I also found these two native javascript functions, the decoder works on my incoming stream, but I still can't get the hex to encode...
我还发现了这两个原生的javascript函数,解码器在我的传入流上工作,但我仍然无法得到十六进制编码...
function encode_utf8( s ) {
return unescape( encodeURIComponent( s ) );
}
function decode_utf8( s ) {
return decodeURIComponent( escape( s ) );
}
2 个解决方案
#1
23
Here's a node.js specific approach, taking advantage of the the Buffer class provided by the node standard lib.
这是node.js特定的方法,利用节点标准lib提供的Buffer类。
https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings
https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings
To get the byte (0-255) value:
要获取字节(0-255)值:
Buffer.from('80', 'hex')[0];
// outputs 128
And to convert back:
并转换回来:
Buffer.from([128]).toString('hex');
// outputs '80'
To convert to utf8:
要转换为utf8:
Buffer.from('80', 'hex').toString('utf8');
#2
2
You can make use of Number.prototype.toString and parseInt.
您可以使用Number.prototype.toString和parseInt。
The key is to make use of the radix
parameters to do the conversions for you.
关键是利用基数参数为您进行转换。
var bytestring = Number('0x' + hexstring).toString(10); // '128'
parseInt(bytestring, 2).toString(16); // '80'
#1
23
Here's a node.js specific approach, taking advantage of the the Buffer class provided by the node standard lib.
这是node.js特定的方法,利用节点标准lib提供的Buffer类。
https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings
https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings
To get the byte (0-255) value:
要获取字节(0-255)值:
Buffer.from('80', 'hex')[0];
// outputs 128
And to convert back:
并转换回来:
Buffer.from([128]).toString('hex');
// outputs '80'
To convert to utf8:
要转换为utf8:
Buffer.from('80', 'hex').toString('utf8');
#2
2
You can make use of Number.prototype.toString and parseInt.
您可以使用Number.prototype.toString和parseInt。
The key is to make use of the radix
parameters to do the conversions for you.
关键是利用基数参数为您进行转换。
var bytestring = Number('0x' + hexstring).toString(10); // '128'
parseInt(bytestring, 2).toString(16); // '80'