2

In Python, I have the following code to store bytes in a variable like: -

K = b"\x00" * 32

I was trying to write a javascript equivalent of this code to get bytes string using the following code:

function toUTF8Array(str) {
  var utf8 = [];
  for (var i = 0; i < str.length; i++) {
    var charcode = str.charCodeAt(i);
    if (charcode < 0x80) utf8.push(charcode);
    else if (charcode < 0x800) {
      utf8.push(0xc0 | (charcode >> 6), 0x80 | (charcode & 0x3f));
    } else if (charcode < 0xd800 || charcode >= 0xe000) {
      utf8.push(
        0xe0 | (charcode >> 12),
        0x80 | ((charcode >> 6) & 0x3f),
        0x80 | (charcode & 0x3f)
      );
    }
    // surrogate pair
    else {
      i++;
      // UTF-16 encodes 0x10000-0x10FFFF by
      // subtracting 0x10000 and splitting the
      // 20 bits of 0x0-0xFFFFF into two halves
      charcode =
        0x10000 + (((charcode & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff));
      utf8.push(
        0xf0 | (charcode >> 18),
        0x80 | ((charcode >> 12) & 0x3f),
        0x80 | ((charcode >> 6) & 0x3f),
        0x80 | (charcode & 0x3f)
      );
    }
  }
  return utf8;
}

But it is generating byte array as follows:

[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

I don't want the output as plain array of numbers. I need the bytes output like Python's (out of the Python code as: K = b"\x00" * 32). How to achieve that?

Somdip Dey
  • 3,346
  • 6
  • 28
  • 60
Suman Saha
  • 101
  • 1
  • 3
  • pythons output is: b'\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\x00\x00\x00\x00' – IT goldman Jul 27 '21 at 19:41
  • @ITgoldman Yes i need the python equivalent of that line of code in js. – Suman Saha Jul 27 '21 at 19:45
  • Instead of an integer array, you need a byte array, did I understand? – AlexSp3 Jul 27 '21 at 19:47
  • @AlexandroPalacios I think the person means a Byte string (not array), same as the output of Python code, is needed. – Somdip Dey Jul 27 '21 at 19:48
  • would applying `String.fromCharCode()` to every X in the array, and then joining it all to one string be a valid solution? – IT goldman Jul 27 '21 at 20:13

0 Answers0