1
0
Fork 0
mirror of https://github.com/CorentinTh/it-tools.git synced 2025-07-18 20:59:37 +02:00
it-tools/src/tools/text-to-binary/text-to-binary.models.ts
2023-10-15 22:57:47 +00:00

22 lines
637 B
TypeScript

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('');
}