diff --git a/index.d.ts b/index.d.ts index a9a91b7..9d130f2 100644 --- a/index.d.ts +++ b/index.d.ts @@ -249,3 +249,16 @@ console.log(hexToUint8Array('48656c6c6f')); ``` */ export function hexToUint8Array(hexString: string): Uint8Array; + +/** +Convert a string to a `Uint8Array` using ASCII encoding. + +@example +``` +import { asciiStringToUint8Array } from 'uint8array-extras'; + +console.log(asciiStringToUint8Array('Hello')); +//=> Uint8Array [72, 101, 108, 108, 111] +``` +*/ +export function asciiStringToUint8Array(string: string): Uint8Array; diff --git a/index.js b/index.js index acf22b4..cae5621 100644 --- a/index.js +++ b/index.js @@ -220,3 +220,19 @@ export function hexToUint8Array(hexString) { return bytes; } + +export function asciiStringToUint8Array(string) { + assertString(string); + + const bytes = new Uint8Array(string.length); + + for (let i = 0; i < string.length; i++) { + const code = string.charCodeAt(i); + if (code > 127) { + throw new Error(`Non-ASCII character detected at position ${i}`); + } + bytes[i] = code; + } + + return bytes; +}