- How do I convert a string to a Uint8Array in node?
- I don't normally develop in Javascript and this is driving me nuts. They offer a conversion
Uint8Array.toString()
but not the other way around. Does anyone know of an easy way for me to do this without creating my own parser? - I have seen some other answers to this, but they don't seem to address this specific class type
Patrick Roberts
52.3k10 gold badges119 silver badges165 bronze badges
asked Jul 10, 2020 at 17:33
-
Similar answer for UTF-8 string to UInt8Array stackoverflow.com/questions/18729405/…nezort11– nezort112024年05月08日 11:47:44 +00:00Commented May 8, 2024 at 11:47
3 Answers 3
You can use Buffer.from(string[, encoding])
. The Buffer
class has implemented the Uint8Array
interface in Node since v4.x. You can also optionally specify an encoding with which to do string processing in both directions, i.e. buffer.toString([encoding])
.
answered Jul 10, 2020 at 17:39
Comments
Why not simply using:
const resEncodedMessage = new TextEncoder().encode(message)
answered Sep 13, 2022 at 9:24
Comments
Uint8Array.from(text.split('').map(letter => letter.charCodeAt(0)));
or (appears about 18% faster):
Uint8Array.from(Array.from(text).map(letter => letter.charCodeAt(0)));
Note: These only work for ASCII, so all the letters are modulo 256, so if you try with Russian text, it won't work.
answered Jun 22, 2021 at 21:13
5 Comments
Heretic Monkey
Answers with explanation of code generally do better than code dumps which leave it to others to interpret. Also,
text.split('')
doesn't work well for Unicode strings; see How to get character array from a string? Octo Poulos
Well you replied just as I was editing the answer. Indeed it's not good for unicode but this method is very simple and fast and might be exactly what he's looking for.
Hashbrown
I'd probably just delete that first code snippet as
Array.from
does respect logical character iteration, and your only issue is charCodeAt
, which I would swap to .codePointAt(0)
(which can return up to a 32bit number); here you can throw an exception, if you really do expect the codepoints to always be below 512.Hashbrown
Btw, this will always work:
Uint8Array.from(encodeURI(text).split(/%|(?<!%.?)/).map((x) => ((x[1]) ? parseInt(x, 16) : x.charCodeAt(x))))
WORMSS
I was just wondering why did you need the array? Cannot you just go straight to
Uint8Array.from(text, letter => letter.charCodeAt(0))
lang-js