1

Trying to migrate the following Python code to Javascript and failing:

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')

This is my Javascript version:

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:

As you can see I succeeded with the first step ba.unhexlify(pData) by using a matching library that someone already moved from Python to JS.

I got stuck in the second step crc_hqx = ba.crc_hqx(unhex, 0x1021), I tried to use 2 different libraries but didn't get the same value as output...

also 'struct' library is not acting the same and returns Array Buffer instead of a string. structJS file is taken from here: https://github.com/lyngklip/structjs

HELP!

NitayBZ
  • 11
  • 2

0 Answers0