简体   繁体   English

如何在Javascript中将十六进制字符串转换为字节,将字节转换为十六进制字符串?

[英]How to convert a hex string to a byte and a byte to a hex string in Javascript?

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 ) );
}

Here's a node.js specific approach, taking advantage of the the Buffer class provided by the node standard lib. 这是node.js特定的方法,利用节点标准库提供的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');

You can make use of Number.prototype.toString and parseInt . 您可以使用Number.prototype.toStringparseInt

The key is to make use of the radix parameters to do the conversions for you. 关键是利用radix参数为您进行转换。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM