* Converts a string to a byte array. * Treats the string as UTF-8 if any values are over 255. * * @param {string} str * @returns {byteArray} * * @example * // returns [72,101,108,108,111] * Utils.strToByteArray("Hello"); * * // returns [228,189,160,2
(str)
| 535 | * Utils.strToByteArray("你好"); |
| 536 | */ |
| 537 | static strToByteArray(str) { |
| 538 | log.debug(`Converting string[${str?.length}] to byte array`); |
| 539 | if (!str) return []; |
| 540 | const byteArray = new Array(str.length); |
| 541 | let i = str.length, b; |
| 542 | while (i--) { |
| 543 | b = str.charCodeAt(i); |
| 544 | byteArray[i] = b; |
| 545 | // If any of the bytes are over 255, read as UTF-8 |
| 546 | if (b > 255) return Utils.strToUtf8ByteArray(str); |
| 547 | } |
| 548 | return byteArray; |
| 549 | } |
| 550 | |
| 551 | |
| 552 | /** |
no test coverage detected