简体   繁体   English

如何在JavaScript中将十六进制数转换为文本字符串(Unicode,而不仅仅是ASCII)(例如PHP的hex2bin)?

[英]How to convert hexadecimal number into a text string (unicode, not just ASCII) (like PHP's hex2bin) in JavaScript?

Let us say that I have a text string that was converted into hexadecimal with PHP. 假设我有一个文本字符串,该文本字符串已用PHP转换为十六进制。 For example: 例如:

<?php
$text = 'hello world';
$text_hex = bin2hex($text);
echo $text_hex; //echos 68656c6c6f20776f726c64
echo '<br>';
echo hex2bin($text_hex); //echos hello world
?>

How do I convert $text_hex , which will be a hexadecimal number, into a text string in JavaScript (just like the function hex2bin() in PHP). 如何将$text_hex十六进制数字$text_hex转换$text_hex JavaScript中的文本字符串(就像PHP中的hex2bin()函数hex2bin() )。

So far I have only found ways to convert the hexadecimal number into a binary number, but not ways to interpret that binary number as a text string. 到目前为止,我只找到了将十六进制数转换为二进制数的方法,但是没有找到将二进制数解释为文本字符串的方法。 So, for example, I managed to make this: 因此,例如,我设法做到了:

 <script>function hex2bin(hex){ var resultado = (parseInt(hex, 16).toString(2)); return resultado; };</script> <div id="test"> </div> hex2bin, write an hexadecimal number here:<br> <input type="text" id="textinput" oninput="document.getElementById('test').innerText = hex2bin(document.getElementById('textinput').value)"><br> <code> hello world = 68656c6c6f20776f726c64</code> 

But that binary number is managed as a number, and I don't get how to interpret it as a text string. 但是那个二进制数是作为一个数字管理的,我不知道如何将其解释为文本字符串。

How could I do it? 我该怎么办?


Edit: 编辑:

Thank you very much to Bharata and to Laurence Mommers for their proposed solutions. 非常感谢Bharata和Laurence Mommers提出的解决方案。 They work but only with ascii characters. 它们有效,但仅适用于ASCII字符。 When it is tried to use others like ñ, ÿ, æ, ç, œ, it does not work. 当尝试使用ñ,ÿ,æ,ç,œ等其他语言时,它不起作用。 I tried even defining the charset as UTF-8 and as latin1 just in case that was the issue but it is not changing anything. 我什至尝试将字符集定义为UTF-8和latin1,以防万一这是问题所在,但没有任何改变。

 <script>function hex2bin(hex){ var resultado = (parseInt(hex, 16).toString(2)); return resultado; }; function hex2a(hexx) { var hex = hexx.toString();//force conversion var str = ''; for (var i = 0; (i < hex.length && hex.substr(i, 2) !== '00'); i += 2) str += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); return str; }; function hexToString(hex) { return hex.match(/../g).map(function(v) { // "+" symbol is for converting from string to integer return String.fromCharCode(+('0x'+v)); }).join('') }; </script> Original failed script UTF-8: <div id="test" charset="UTF-8"> </div> Laurence Mommers's script UTF-8: <div id="test1" charset="UTF-8"> </div> Bharata's script UTF-8: <div id="test2" charset="UTF-8"> </div> Original failed script ISO-8859-1: <div id="test3" charset="ISO-8859-1"> </div> Laurence Mommers's script ISO-8859-1: <div id="test4" charset="ISO-8859-1"> </div> Bharata's script ISO-8859-1: <div id="test5" charset="ISO-8859-1"> </div> <br>Write an hexadecimal number here:<br> <input type="text" id="textinput" oninput="document.getElementById('test').innerText = hex2bin(document.getElementById('textinput').value); document.getElementById('test1').innerText = hex2a(document.getElementById('textinput').value); document.getElementById('test2').innerText = hexToString(document.getElementById('textinput').value); document.getElementById('test3').innerText = hex2bin(document.getElementById('textinput').value); document.getElementById('test4').innerText = hex2a(document.getElementById('textinput').value); document.getElementById('test5').innerText = hexToString(document.getElementById('textinput').value)"><br> <code> php bin2hex('hello world') = 68656c6c6f20776f726c64</code> <br> <code> php bin2hex('ñ, ÿ, æ, ç, œ') = c3b12c20c3bf2c20c3a62c20c3a72c20c593</code> 

My guess is that the method fromCharCode() is using a different charset to the one that php is using. 我的猜测是fromCharCode()方法使用的字符集与php使用的字符集不同。 Perhaps there is a way to make it use the charset that php uses? 也许有一种方法可以使其使用php使用的字符集? Or to make the hexadecimal conversion to the charset of javascript? 还是将十六进制转换为javascript的字符集? Does this charset varies per browser? 每个浏览器的字符集是否不同?

You could try this solution: 您可以尝试以下解决方案:

 function hexToString(hex) { return hex.match(/../g).map(function(v) { // "+" symbol is for converting from string to integer return String.fromCharCode(+('0x'+v)); }).join('') } var text_hex = '68656c6c6f20776f726c64'; console.log(hexToString(text_hex)); //hello world 

This should also work for non ascii characters. 这也适用于非ASCII字符。 the decodeURIComponent(escape(x)) solution is not the nicest solution, but it is the only way i know of for converting to UTF-16 decodeURIComponent(escape(x))解决方案不是最好的解决方案,但这是我知道的唯一转换为UTF-16的方法

 <div id="test"></div> <script> function hex2a(hexx) { var hex = hexx.toString(); // Force string conversion var array = []; for (var i = 0; (i < hex.length && hex.substr(i, 2) !== '00'); i += 2) array.push(parseInt(hex.substr(i, 2), 16)); return decodeURIComponent(escape(String.fromCharCode.apply(null, array))); } document.getElementById('test').innerText = hex2a("c3b12c20c3bf2c20c3a62c20c3a72c20c5932c2068656c6c6f20776f726c64"); </script> 

The encoding of the php ouput is utf-8 : 0xc3, 0xb1 -> U+00F1 = 'ñ' . php输出的编码为utf-8: 0xc3, 0xb1 -> U+00F1 = 'ñ'

To decode a string containing a sequence of hexadecimal pairs in javascript you can insert a '%' before each pair of hexadecimal characters (with regex), and then parse the new string with decodeURIComponent which decode escaped utf-8 sequences to string characters : 要在javascript中解码包含十六进制对序列的字符串,您可以在每对十六进制字符(使用regex)之前插入一个'%' ,然后使用带有解码decodeURIComponent的新字符串进行解析,该字符串将转义的utf-8序列解码为字符串字符:

function hex2string(hex)
{
  try {
    return decodeURIComponent((hex || '').replace(/([0-9A-Fa-f]{2})/g, '%$1'));
  }
  catch (URIError) {
    return '\ufffd';
  }
}

Here a code snippet to test hex2string : 这是一个测试hex2string的代码片段:

 <script> function hex2string(hex) { try { return decodeURIComponent((hex || '').replace(/([0-9A-Fa-f]{2})/g, '%$1')); } catch (URIError) { return '\�'; } } </script> <div id="test"> </div> <br>Write an hexadecimal number here:<br> <input type="text" id="textinput" oninput="document.getElementById('test').innerText = hex2string(document.getElementById('textinput').value)"><br> <code> php bin2hex('hello world') = 68656c6c6f20776f726c64</code> <br> <code> php bin2hex('ñ, ÿ, æ, ç, œ') = c3b12c20c3bf2c20c3a62c20c3a72c20c593</code> 

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

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