diff options
author | 2023-10-16 00:57:47 +0200 | |
---|---|---|
committer | 2023-10-15 22:57:47 +0000 | |
commit | b2ad4f7a27d1feaf0ef58042689124fc51c54d1e (patch) | |
tree | 904208593bd17b20b026f996a2a1b65e6b607f8c /src/tools/text-to-binary/text-to-binary.models.ts | |
parent | b408df82c1d8a0123e552048421b37afcf5189c6 (diff) | |
download | it-tools-b2ad4f7a27d1feaf0ef58042689124fc51c54d1e.tar.gz it-tools-b2ad4f7a27d1feaf0ef58042689124fc51c54d1e.tar.zst it-tools-b2ad4f7a27d1feaf0ef58042689124fc51c54d1e.zip |
feat(new tool): text to ascii converter (#669)
Diffstat (limited to 'src/tools/text-to-binary/text-to-binary.models.ts')
-rw-r--r-- | src/tools/text-to-binary/text-to-binary.models.ts | 22 |
1 files changed, 22 insertions, 0 deletions
diff --git a/src/tools/text-to-binary/text-to-binary.models.ts b/src/tools/text-to-binary/text-to-binary.models.ts new file mode 100644 index 0000000..ad9699a --- /dev/null +++ b/src/tools/text-to-binary/text-to-binary.models.ts @@ -0,0 +1,22 @@ +export { convertTextToAsciiBinary, convertAsciiBinaryToText }; + +function convertTextToAsciiBinary(text: string, { separator = ' ' }: { separator?: string } = {}): string { + return text + .split('') + .map(char => char.charCodeAt(0).toString(2).padStart(8, '0')) + .join(separator); +} + +function convertAsciiBinaryToText(binary: string): string { + const cleanBinary = binary.replace(/[^01]/g, ''); + + if (cleanBinary.length % 8) { + throw new Error('Invalid binary string'); + } + + return cleanBinary + .split(/(\d{8})/) + .filter(Boolean) + .map(binary => String.fromCharCode(Number.parseInt(binary, 2))) + .join(''); +} |