javascript - 将 python 签名代码转换为 javascript
问题描述
我目前正在开发代码生成器并将其移植到 javascript,但是我似乎无法获得相同的结果?
我在 Python 中得到的代码如下:
def sign(self, cs, api):
temp_string = ""
cs_length = len(cs)
api_length = len(api)
if api_length > 0:
for index in range(0, cs_length):
temp_char = cs[index]
temp_code = ord(temp_char)
temp_code_2 = ord(api[index % api_length])
new_code = self.get_code(temp_code, 47, 57, temp_code_2)
new_char = ""
if new_code != cs[index]:
new_char = chr(new_code)
try:
temp_string += new_char
except:
xbmc.log("Unprintable character => %s" % new_char)
xbmc.log("Index: %i\tCharacter %i:%s\t\tModulus %i\t\tModulus Code %i:%s\t\tNew Code %i:%s" %
(index, temp_code, temp_char, (index % api_length), temp_code_2, chr(temp_code_2), new_code,
new_char))
else:
xbmc.log("Signature cannot be blank")
# xbmc.log("\r\nTarget Signature: 7a74G7m23Vrp0o5c")
xbmc.log("Result signature: %s" % temp_string[0:16])
return temp_string[0:16]
def get_code(self, char_code, const_1, const_2, char_result):
if const_1 < char_code <= const_2:
char_code += char_result % (const_2 - const_1)
if char_code > const_2:
char_code = char_code - const_2 + const_1
return char_code
这是我用 Javascript 写的:
get_code(char_code, const_1, const_2, char_result) {
if(const_1 < char_code <= const_2) {
char_code += char_result % (const_2 - const_1);
if(char_code > const_2) {
char_code = char_code - const_2 + const_1;
}
}
return char_code;
}
sign(cs, api) {
let temp_string = '';
let cs_length = cs.length;
let api_length = api.length;
if(api_length > 0) {
for(let index in this.range(0, cs_length)) {
let temp_char = cs[index];
let temp_code = temp_char.charCodeAt(0);
let temp_code_2 = api[index % api_length].charCodeAt(0);
let new_code = this.get_code(temp_code, 47, 57, temp_code_2);
let new_char = "";
if(new_code != cs[index]) {
try {
new_char = new_code.charCodeAt(0);
temp_string += new_char;
} catch(error) {
console.log('"Unprintable character => ' + new_char);
}
}
}
}
return temp_string.substring(0, 16);
}
在 Javascript 中运行它时,我只是得到了大量的"Unprintable character =>
结果?
解决方案
您的问题似乎是您从此 Python 代码的转换
new_char = chr(new_code)
到 JavaScript
new_char = new_code.charCodeAt(0);
鉴于chr
在 Python 中采用 anint
并返回单个 length str
,而String.charCodeAt
恰恰相反 - 还鉴于 的值new_code
似乎是 an Number
or int
(分别在 JavaScript 和 Python 中),这根本不起作用,因为这不是可用于的方法Number
类型。
如果代码记录了块error
内的实际情况就很清楚了catch
——异常的性质应该已经表明了这一点TypeError: new_code.charCodeAt is not a function
。
您可能正在寻找String.fromCharCode
,因此有问题的行应该是:
new_char = String.fromCharCode(new_code);
推荐阅读
- php - file_get_contents 输出错误请求 PHP
- elixir - 如何使用 Pow 验证 Phoenix 套接字?
- python - 如何根据列将 numpy 数组拆分为 numpy 数组?
- python - 如何获取不同列表的相同索引并将其放入单独的列表中?
- docker - RabbitMQ pod web 用户名和密码?
- python - 如何在不丢失曲线自然对数的情况下找到值
- c++ - 无法使用地图
除非我为 Custom_Class 定义没有参数的默认构造函数 - python - Keras 中的 flow_from_directory 方法是否会调整图像的大小,即使它们已经匹配所需的大小?
- cakephp - 如何在 cakephp 3.x 中使用子域
- sas - 如何按开始日期/结束日期对的时间顺序排列 SAS 数据集