节点js中的PHP函数"/>
节点js中的PHP函数
试图将以下PHP函数转换为Node.js,但两者均显示不同的输出。out.node.js函数应该与PHP相等。以下是我尝试过的代码。我还附加了hexdump值。
PHP
function hextobin() {
$hexString = 'd41d8cd98f00b204e9800998ecf8427e';
$length = strlen($hexString);
$binString = "";
$count = 0;
while ($count < $length) {
$subString = substr($hexString, $count, 2);
$packedString = pack("H*", $subString);
if ($count == 0) {
$binString = $packedString;
} else {
$binString .= $packedString;
}
$count += 2;
}
return $binString;
}
Output = ��ُ�� ���B~
Hexdump -C value of above output =
00000000 ef bf bd 1d ef bf bd d9 8f ef bf bd 04 ef bf bd |................|
00000010 20 ef bf bd ef bf bd ef bf bd 42 7e 0a | .........B~.|
0000001d
Node.JS
exports.hex2bin = () => {
let hexString = 'd41d8cd98f00b204e9800998ecf8427e';
let binString ="";
let length = hexString.length;
let count = 0;
while (count < length) {
const sub = hexString.substr(count, 2);
let packedString = Buffer.from(sub, "hex");
if (count === 0) {
binString = packedString;
} else {
binString += packedString;
}
count += 2;
}
return binString;
};
Output = ������� ���B~
Hexdump -C value of above output =
00000000 ef bf bd 1d ef bf bd ef bf bd ef bf bd ef bf bd |................|
00000010 04 ef bf bd ef bf bd 20 ef bf bd ef bf bd ef bf |....... ........|
00000020 bd 42 7e 0a |.B~.|
00000024
任何帮助将不胜感激。
回答如下:在PHP中,字符串没有内部编码。它只是一系列字节。在Javascript中,字符串为UTF-16。为了处理等同于节点中php字符串的内容,Buffer类已经是一个无符号8位字节的数组。您正在使用的实用程序函数将一次性读取整个十六进制字符串,而不是转换每对十六进制字符。
概念证明:
let hex2bin = () => {
let hexString = 'd41d8cd98f00b204e9800998ecf8427e';
let packedString = Buffer.from(hexString, "hex");
return packedString.toString(undefined);
};
let foo = hex2bin();
console.log(foo);
hexdump
$ node test.js | hexdump -C
00000000 ef bf bd 1d ef bf bd d9 8f 00 ef bf bd 04 ef bf |................|
00000010 bd 09 ef bf bd ef bf bd ef bf bd 42 7e 0a |...........B~.|
0000001e
更多推荐
节点js中的PHP函数
发布评论