C functions to Javascript



我正在尝试将 2 个函数从 C 转换为 Javascript,但我失败了。

我尝试转换的 C 函数是:

void encrypt(char password[],int key)
{
unsigned int i;
for(i=0;i<strlen(password);++i)
{
password[i] = password[i] - key;
}
}
void decrypt(char password[],int key)
{
unsigned int i;
for(i=0;i<strlen(password);++i)
{
password[i] = password[i] + key;
}
}

C 函数来自: http://c-program-example.com/2012/04/c-program-to-encrypt-and-decrypt-a-password.html

我在Javascript中所做的是这样的:

var password = "hello"
var key = 322424;
for (var i=0; i<password.length; i++) {
var char = password[i].charCodeAt();

var s = String.fromCharCode(char-key);

alert(s);
}  

在将它们作为函数之前,我正在放置警报以查看它是否正常工作。有人可以告诉我如何在 Js 中正确完成吗?

试试这个,正如 Clifford 在评论中所说,每个字符代码都必须被屏蔽为 modulo-256,因为大小为char.另外,由于decrypt相同但key减法,我重用了encryptkey为负数。

在这里你有一个工作片段,让我知道它是否提供了所需的输出。

function encrypt (password, key) {
var i,
output = '';
for (i = 0; i < password.length; i++) {
var charCode = password.charCodeAt(i),
keyedCharCode = (charCode - key) & 0xff;
output += String.fromCharCode(keyedCharCode);
}
return output;
}
function decrypt (password, key) {
return encrypt(password, -key);
}
var password = 'hello',
key = 322424,
encrypted = encrypt(password, key),
decrypted = decrypt(encrypted, key);
console.log('encrypt', encrypted);
console.log('decrypt', decrypted);

C 中的Achar实际上是一个小整数,其中 six 中的值从00FFchar在许多实现中都是有符号的(unsigned char不是(,所以它的值从-128127(总共256个值,如果没有符号,则0255(。字符数组,char[]是一个微小整数的数组,通常 C 中"字符串"的最后一个字符是标记结束的字节0x00(例如,printf知道当满足字节0时结束就在那里(。

在Javascript中,字符串是一组Unicode字符。

在 C 中,

char s[] = "hello";
int k = 322424;
char *t = s;
while(*t) *t++ -= k; // 't' is the encoded version of 's'
// print the integer values of the new encoded 'string'
for(t=s ; *t ; t++) printf("%d ", *t); // -16 -19 -12 -12 -9
// (unsigned: 240 237 244 244 247, or add 256 to negative values above)
printf("n");

char不能包含多个字节。

在 Javascript 中,您必须将结果数字保留在字节范围内,否则可能会存储多字节字符。例如

String.fromCharCode(0x3042)  gives "あ" (Unicode [character 0x3042](https://www.key-shortcut.com/en/writing-systems/%E3%81%B2%E3%82%89%E3%81%8C%E3%81%AA-japanese/))

在 C 中,

char c = 0x3042; // will only keep one byte, the LSB, 0x42

因此,在Javascript中,尝试类似的东西

var s = "hello";
var k = 322424;
var i,l = s.length;
var t = '';
// Note the `& 0xff` that keep the result within a byte range
for(i=0 ; i<l ; i++) t += String.fromCharCode((s.charCodeAt(i) - k) & 0xff);
// 't' is the result, let see its char codes
var u = '';
for(i=0 ; i<l ; i++) u += t.charCodeAt(i) + ' ';
console.log(u);  // 240 237 244 244 247 (same as in C, 240-256 = -16 ...)

JS字符代码是无符号的,因此是积极的结果。它们与 C 中的相同。

最新更新