I am trying to convert a byte array into a string and then send it over a socket to a remote server. I have successfully prototyped the code in Python and am trying to migrate it to Javascript.
For some reason, there is a discrepancy in the last character between the two languages.
Python Code
def make_checksum(data):
num = 0x00
for num2 in data:
num = (num + num2) & 0xFF
return num
data = [0x56, 0x54, 0x55, 0x3E, 0x28, 0x00, 0x08,
0x00, 0x03, 0x01, 0x46, 0x00, 0x00, 0x00, 0xC0]
message = bytearray(data + [make_checksum(data)])
Javascript
function checksum(data) {
let res = 0x00
for (let i = 0; i < data.length; ++i) {
res = (res + data[i]) & 0xFF
}
return String.fromCharCode(res)
}
let data = new Int8Array([0x56, 0x54, 0x55, 0x3E, 0x28, 0x00,
0x08, 0x00, 0x03, 0x01, 0x46, 0x00, 0x00, 0x00, 0xC0])
let message = String.fromCharCode(...data) + checksum(data)
I think this might have something to do with the difference between ascii and UTF.
checksum(data)instead ofchecksum(0xC0)? Should the python be doingbytearray(data + [make_checksum(data)])?messageis bytes, you shouldn’t represent it with a string in JavaScript. Leave it as aUint8Array.stream.writeaccepts a buffer.Buffer.concat([Buffer.from([0x56, 0x54, 0x55, 0x3E, 0x28, 0x00, 0x08, 0x00, 0x03, 0x01, 0x46, 0x00, 0x00, 0x00, 0xC0]), checksum(data)]), wherechecksumalso returns aBuffer.