Reputation: 5
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].
Upvotes: -3
Views: 1576
Reputation: 2192
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.
Upvotes: 0
Reputation: 1833
Finally, a javascript string content may eventually be larger 64KB or larger, so its string length after conversion to bytes may not fit in a 16-bit integer or 2 bytes. The minimum code should first check for the string length (throw an error if st.length>=32768
), then use a 2-bytes buffer (from Buffer.alloc(2)
) before outputing to the buffer the string length with buffer.writeUInt16BE(st.length)
.
It's generally a bad idea to make code that cannot handle correct string contents: a text with 32768 characters or more is not at all exceptional. But it may be correct if the text comes from a database field with length limitations, not if the text comes from user input in an HTML input form field, which would first require validation (even if that form was using VALID UTF-8, that the validator should still check: don't assume that the "user" is using a browser, it could be a malicious bot trying to break your webapp to harvest security holes and get some privileges or steal private data.
On the web, input validation (valid encoding, length limits, text format) from submitted form data is required for ALL input fields (including combo selectors and radio buttons or checkboxes) before ALL processings (but you may want to discard all unknown fields with incorrect names). Make sure that your processing can handle all text lengths that pass the validators of your webapp (including self-contained applications using an embedded web component, like mobile apps or desktop apps, not just web browsers).
IMHO, it's just bad to use such 16-bit assumption, but your question is valid if you make sure that validators and implemented and length constraints are already checked before.
Upvotes: 0