编程语言
首页 > 编程语言> > 什么是javascript中的等效php chr()和ord()函数

什么是javascript中的等效php chr()和ord()函数

作者:互联网

我在php代码中使用了bitwise运算符,它返回base64中的解码字符串.我希望实现php代码与javascript相同.据我所知,chr()等效于String.fromCharCode(n)和ord()是n.charCodeAt(0).但最终输出都不同.

PHP代码: –

<?php
$pass = "RuvEtrUt74gaDR5DufuChe";
$en = "";
foreach(str_split($pass) as $chr){
    $b1=((($chr = ord($chr)) >> 1) & 0xFF);
    $b2=($chr << (8 - 1));
     $en = $en.chr( $b1|$b2 );
}
$en = base64_encode($en); //Output:- )º;¢:9ª:›³°")š"º3º¡4²
echo ($en);
echo (base64_decode($en)); //Output:- Kbo7ojo5qjqbGrOwIimaIrozuqE0sg==

在Javascript代码: –

var pass = "RuvEtrUt74gaDR5DufuChe";
var en = "";
var passArr = pass.split('');
for (var i = 0; i < passArr.length; i++) {
    var b1 = (((passArr[i] = passArr[i].charCodeAt(0)) >> 1) & 0xFF);
    var b2 = (passArr[i] << (8 - 1));
    en += chr(b1 | b2);
}
console.log('en',en);//Output:- ⤩㪺㬻⊢㨺㤹⪪㨺ᮛᨚ㎳グ∢⤩᪚∢㪺㌳㪺↡㐴㊲
en = window.btoa(unescape(encodeURIComponent(en)));
console.log('en', en);//Output:- 4qSp46q646y74oqi46i646S54qqq46i64a6b4aia446z44Kw4oii4qSp4aqa4oii46q644yz46q64oah45C044qy
                     //need same as in php i.e, :- Kbo7ojo5qjqbGrOwIimaIrozuqE0sg==
function chr(codePt) {
    if (codePt > 0xFFFF) {
        codePt -= 0x10000
        return String.fromCharCode(0xD800 + (codePt >> 10), 0xDC00 + (codePt & 0x3FF))
    }
    return String.fromCharCode(codePt)
}

正如您所看到的,javscript输出与php输出不同.我需要javascript中的确切输出,它返回PHP代码.谢谢

解决方法:

var res = String.fromCharCode(65);

此函数与chr()函数在javascript中返回字符的效果相同.

标签:javascript,base64,encoding,bitwise-operators
来源: https://codeday.me/bug/20191007/1867246.html