Search code examples
javascriptnode.jsbitconverter

Convert javascript string length to array of byte[]


I need to convert in javascript the length of a string to an array of bytes with length 2 (16-bit signed integer) equivalent to C# Bitconverter.GetBytes( short value).

Example: 295 -> [1,39].


Solution

  • As you are using node, a Buffer is what you need. Check out the documentation here. For example:

    //Make a string of length 295
    const st="-foo-".repeat(59);
    //Create a byte array of length 2
    const buf = Buffer.alloc(2);
    //Write the string length as a 16-bit big-endian number into the byte array
    buf.writeUInt16BE(st.length, 0);
    console.log(buf);
    //<Buffer 01 27> which is [1, 39]
    

    Be aware that this will give you the string length in characters, not the byte length of the string - the two may be the same but that is not guaranteed.