aboutsummaryrefslogtreecommitdiff
path: root/src/tools/text-to-binary/text-to-binary.models.ts
blob: ad9699af63cc886c198c77c752aa44b8e8260662 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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('');
}