简体   繁体   English

JavaScript hex2bin实现

[英]JavaScript hex2bin implementation

I tried to implement a JS analogue of PHP's hex2bin . 我试图实现PHP的hex2bin的JS类似物。 I found a few versions of hex2bin in JS, but all of these show the same result, which is different from the PHP result. 我在JS中找到了hex2bin的几个版本,但是所有这些都显示相同的结果,这与PHP结果不同。

For example, a string 440EF96DB9A2225C32E031659DF2608B49932F0D8AFAC46F74FA56FF3E1AE952 looks like this: 例如,字符串440EF96DB9A2225C32E031659DF2608B49932F0D8AFAC46F74FA56FF3E1AE952如下所示:

在此处输入图片说明

As I can see, the results are very similar, but still different. 如我所见,结果非常相似,但仍然不同。 What can be wrong? 有什么事吗

Nothing is wrong. 没有错误。 The results are the same, but strings are visualised differently. 结果相同,但是字符串的显示方式不同。 PHP and JavaScript output certain characters differently. PHP和JavaScript输出某些字符的方式有所不同。 Take for instance the character with code point 249: 以代码点为249的字符为例:

echo chr(249);
// Equivalent to 
echo hex2bin("F9");

The output is " ". 输出为“。”。

While in JavaScript the output of the same character is "ù": 在JavaScript中,相同字符的输出为“ù”:

 console.log(String.fromCharCode(249)); 

Other characters may not be visible at all in one, but visible in the other. 其他字符可能完全看不到,但在另一个中可见。 Both languages differ in internal character encoding which may also play a role in their rendering of strings. 两种语言的内部字符编码不同,这在它们的字符串呈现中也可能起作用。

If you want to ensure that they are the same, then represent the hex2bin output in base64 encoding: 如果要确保它们相同, hex2bin base64编码表示hex2bin输出:

In PHP ( base64_encode ): 在PHP( base64_encode )中:

base64_encode(hex2bin("440EF96DB9A2225C32E031659DF2608B49932F0D8AFAC46F74FA56FF3E1AE952"));

In JavaScript ( btoa ): 在JavaScript( btoa )中:

 const hex2bin = s => s.match(/../g).map(c => String.fromCharCode(parseInt(c, 16))).join``; console.log(btoa(hex2bin("440EF96DB9A2225C32E031659DF2608B49932F0D8AFAC46F74FA56FF3E1AE952"))); 

Both output: 两种输出:

RA75bbmiIlwy4DFlnfJgi0mTLw2K+sRvdPpW/z4a6VI= RA75bbmiIlwy4DFlnfJgi0mTLw2K + sRvdPpW / z4a6VI =

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

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