Попытка перенести код из Python в JavaScript и придерживаться кодирования / вычисления - PullRequest
1 голос
/ 03 ноября 2019

Попытка перенести следующий код Python в Javascript и ошибка:

import binascii as ba
import struct

pData = "fef052000232a100000000003400010000000000000000003317bb5d00000000000000000000f0fe1c003f9800003835373200000000000000000000000000000000000000000000000000000000"
print("pdata: ", pData)
# output: ('pdata: ', 'fef052000232a100000000003400010000000000000000003317bb5d00000000000000000000f0fe1c003f9800003835373200000000000000000000000000000000000000000000000000000000')

unhex = ba.unhexlify(pData)
print("unhex: ", unhex)
# output: ('unhex: ', '\xfe\xf0R\x00\x022\xa1\x00\x00\x00\x00\x004\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x003\x17\xbb]\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0\xfe\x1c\x00?\x98\x00\x008572\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
# this output equals to 'þðR2¡43»]ðþ?8572'

crc_hqx =  ba.crc_hqx(unhex, 0x1021)
print("crc_hqx: ", crc_hqx)
# output: ('crc_hqx: ', 7246)

structP =  struct.pack('>I', crc_hqx)
print("structP: ", structP)
# output: ('structP: ', '\x00\x00\x1cN')
# this output equals to 'N'

hexlify =  ba.hexlify(structP)
print("hexlify: ", hexlify)
# output: ('hexlify: ', '00001c4e')

Это моя версия Javascript:

var ba = require('binascii');
const structJS = require('./structjs');
const nodeCrc = require('node-crc');
const crc = require('crc');

var pData = 'fef052000232a100000000003400010000000000000000003317bb5d00000000000000000000f0fe1c003f9800003835373200000000000000000000000000000000000000000000000000000000'
console.log("pdata: ", pData)
// output: pdata:  fef052000232a100000000003400010000000000000000003317bb5d00000000000000000000f0fe1c003f9800003835373200000000000000000000000000000000000000000000000000000000

var unhex = ba.unhexlify(pData)
console.log("unhex ", unhex)
// output: unhex  þðR2¡43»]ðþ?8572

var crc_hqx =  nodeCrc.crc16ccitt(Buffer.from(unhex, 'utf-8')).toString('hex')
console.log("crc_hqx ", crc_hqx)
// output: crc_hqx  3eee

var crc_hqx =  crc.crc16ccitt(unhex, 0x1021)
console.log("crc_hqx(2) ", crc_hqx)
// output: crc_hqx(2)  62840


var struct = structJS('>I')
var structP = struct.pack(crc_hqx)
console.log("structP ", structP)
// output: structP  ArrayBuffer { [Uint8Contents]: <00 00 f5 78>, byteLength: 4 }

var hexlify =  ba.hexlify(structP)
console.log("hexlify: ", hexlify)
// output: hexlify:

Как вы видите, мне удалось выполнить первый шаг ba.unhexlify(pData) используя подходящую библиотеку, которую кто-то уже перевел из Python в JS.

Я застрял на втором шаге crc_hqx = ba.crc_hqx(unhex, 0x1021), я попытался использовать 2 разные библиотеки, но не получил одно и то же значение в качестве вывода...

также библиотека 'struct' не действует так же, и возвращает строку Array Buffer вместо строки. Файл structJS взят здесь: https://github.com/lyngklip/structjs

HELP!

...