0

How can I convert a string in bytearray using JavaScript. Output should be equivalent of the below Python code.

string2 = '68 03 01 00 22 aa 04 9e 04 4a c2 01 4a 3c 4a c2 01 4a 3c 4a 3c 4a 3c 4a 3c 4a c2 01 4a c2 01 4a 3c 4a 3c 4a c2 01 4a 3c 4a 3c 4a 3c 4a 3c 4a 3c 4a c2 01 4a 3c 4a 3c 4a 3c 4a 3c 4a 3c 49 c2 01 49 c2 01 49 c2 01 4a c2 01 49 c2 01 4a c2 01 4a c2 01 49 c2 01 4a c2 01 4a c2 01 4a c2 01 4a c2 01 4a c2 01 4a c2 01 4a c2 01 4a c2 01 4a c2 01 4a 3c 4a c2 01 4a 3c 4a 3c 4a c2 01 4a c2 01 49 c2 01 4a c2 01 4a 84 05 ab 04 9e 04 4a 3c 49 c3 01 47 3f 47 c5 01 47 c5 01 4a c2 01 4d bf 01 49 3d 48 3d 46 c6 01 44 c8 01 44 42 44 c8 01 47 c5 01 47 c5 01 47 c5 01 47 c5 01 46 3f 46 c6 01 46 c6 01 46 c6 01 46 c6 01 46 c6 01 46 3f 46 30 46 40 46 40 46 40 46 40 46 40 46 40 45 40 46 40 45 40 45 40 45 40 45 43 42 43 42 43 42 43 42 ca 01 42 44 42 ca 01 41 cb 01 41 44 41 44 41 44 41 44 41 45 16'
    
    
data1 = bytearray.fromhex(string2)
for data in data1:
                hex_byte = ("{0:02x}".format(data))
                #print (hex_byte)
                hex_byte = bytearray.fromhex(hex_byte)
                #print (hex_byte)
  • can you share the sample output? – ahsan Jun 06 '22 at 06:22
  • There is nothing like a byte in JavaScript. So if it’s ok that you get an integer array it’s possible. Otherwise not – Thallius Jun 06 '22 at 06:30
  • Is this in the browser or NodeJS? If in NodeJS, you can use [`Buffer`](https://nodejs.org/api/buffer.html) for this. You can then output it as hex using [`buffer.toString('hex')`](https://nodejs.org/api/buffer.html#buftostringencoding-start-end). In the browser it's not quite so easy, but there are ways to do it - see https://stackoverflow.com/questions/40031688/javascript-arraybuffer-to-hex for some ideas. – David Alexander Jun 06 '22 at 06:54

0 Answers0