w

API Reference

This document provides technical details about the Text to ASCII Binary Converter implementation, including conversion algorithms, data structures, and integration options.

Conversion Algorithms

Text to Binary Conversion

Algorithm Overview

function textToBinary(text, encoding = 'utf8', format = 'spaced') {
  const bytes = new TextEncoder().encode(text);
  const binaryArray = [];

  for (let byte of bytes) {
    const binary = byte.toString(2).padStart(8, '0');
    binaryArray.push(binary);
  }

  return formatBinary(binaryArray, format);
}

Step-by-Step Process

  1. Text Encoding: Convert text to byte array using specified encoding
  2. Byte Processing: Process each byte individually
  3. Binary Conversion: Convert each byte to 8-bit binary string
  4. Padding: Ensure each binary string is exactly 8 bits
  5. Formatting: Apply selected formatting (spaced, continuous, grouped)

Encoding Support

  • UTF-8: Multi-byte Unicode encoding
  • ASCII: 7-bit character encoding (0-127)
  • Latin-1: 8-bit extended ASCII (0-255)

Binary to Text Conversion

Algorithm Overview

function binaryToText(binaryString, encoding = 'utf8') {
  // Remove spaces and validate
  const cleanBinary = binaryString.replace(/\s/g, '');

  if (cleanBinary.length % 8 !== 0) {
    throw new Error('Binary length must be a multiple of 8');
  }

  const bytes = [];
  for (let i = 0; i < cleanBinary.length; i += 8) {
    const byteString = cleanBinary.substr(i, 8);
    const byte = parseInt(byteString, 2);
    bytes.push(byte);
  }

  return new TextDecoder().decode(new Uint8Array(bytes));
}

Step-by-Step Process

  1. Input Validation: Check for valid binary characters (0s and 1s)
  2. Length Validation: Ensure length is multiple of 8
  3. Grouping: Split binary string into 8-bit groups
  4. Decimal Conversion: Convert each 8-bit group to decimal
  5. Character Reconstruction: Convert decimal values to characters
  6. Text Assembly: Combine characters into final text

Data Structures

Input Validation

Binary Input Validation

function validateBinaryInput(binaryString) {
  const cleanBinary = binaryString.replace(/\s/g, '');

  // Check for valid characters
  if (!/^[01]+$/.test(cleanBinary)) {
    throw new Error('Invalid binary input. Please enter only 0s and 1s.');
  }

  // Check length
  if (cleanBinary.length === 0) {
    throw new Error('No valid binary characters found in input.');
  }

  if (cleanBinary.length % 8 !== 0) {
    throw new Error('Binary length must be a multiple of 8.');
  }

  return cleanBinary;
}

Character Code Validation

function validateCharacterCode(charCode) {
  if (charCode < 0 || charCode > 255) {
    throw new Error('Invalid character code found in binary input.');
  }
  return charCode;
}

Formatting Functions

Binary Formatting

function formatBinary(binaryArray, format) {
  switch (format) {
    case 'spaced':
      return binaryArray.join(' ');
    case 'continuous':
      return binaryArray.join('');
    case 'grouped':
      return binaryArray.join(' ');
    default:
      return binaryArray.join(' ');
  }
}

Output Statistics

function calculateStats(input, output) {
  return {
    inputLength: input.length,
    outputLength: output.length,
    compressionRatio: (output.length / input.length).toFixed(2),
  };
}

History Management

History Data Structure

interface HistoryRecord {
  id: string;
  textInput: string;
  binaryInput: string;
  encoding: string;
  binaryFormat: string;
  inputLength: number;
  outputLength: number;
  timestamp: number;
}

History Operations

// Add to history
function addToHistory(record) {
  const history = getHistory();
  history.unshift(record);

  // Limit to 50 records
  if (history.length > 50) {
    history.splice(50);
  }

  saveHistory(history);
}

// Load from history
function loadFromHistory(record) {
  return {
    textInput: record.textInput,
    binaryInput: record.binaryInput,
    encoding: record.encoding,
    binaryFormat: record.binaryFormat,
  };
}

Error Handling

Error Types

const ERROR_TYPES = {
  INVALID_BINARY_INPUT: 'Invalid binary input. Please enter only 0s and 1s.',
  BINARY_LENGTH_ERROR: 'Binary length must be a multiple of 8.',
  NO_VALID_BINARY_CHARS: 'No valid binary characters found in input.',
  INVALID_CHAR_CODE: 'Invalid character code found in binary input.',
};

Error Handling Strategy

function handleConversionError(error) {
  const errorMessages = {
    'Invalid binary input': 'invalidBinaryInput',
    'Binary length must be a multiple of 8': 'binaryLengthError',
    'No valid binary characters found': 'noValidBinaryChars',
    'Invalid character code': 'invalidCharCode',
  };

  const errorKey = errorMessages[error.message] || 'conversionError';
  return t(`tools.text-to-ascii-binary.${errorKey}`);
}

Performance Considerations

Memory Management

  • Input Limits: Reasonable limits to prevent memory issues
  • Garbage Collection: Proper cleanup of temporary objects
  • Efficient Algorithms: Optimized conversion functions

Browser Compatibility

  • TextEncoder/TextDecoder: Modern browser support
  • Fallback Options: Alternative implementations for older browsers
  • Feature Detection: Check for API availability

Integration Options

Standalone Usage

// Import conversion functions
import { textToBinary, binaryToText } from './converter';

// Use in your application
const binary = textToBinary('Hello', 'utf8', 'spaced');
const text = binaryToText('01001000 01100101 01101100 01101100 01101111');

Component Integration

<template>
  <div>
    <textarea v-model="input" @input="convert"></textarea>
    <textarea v-model="output" readonly></textarea>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { textToBinary } from './converter';

const input = ref('');
const output = ref('');

function convert() {
  try {
    output.value = textToBinary(input.value);
  } catch (error) {
    output.value = error.message;
  }
}
</script>

Testing

Unit Tests

describe('Text to Binary Conversion', () => {
  test('converts simple text', () => {
    expect(textToBinary('A')).toBe('01000001');
  });

  test('handles multiple characters', () => {
    expect(textToBinary('AB')).toBe('01000001 01000010');
  });

  test('validates binary input', () => {
    expect(() => binaryToText('0100000')).toThrow();
  });
});

Integration Tests

describe('Full Conversion Cycle', () => {
  test('text to binary to text', () => {
    const original = 'Hello';
    const binary = textToBinary(original);
    const converted = binaryToText(binary);
    expect(converted).toBe(original);
  });
});

Security Considerations

Input Sanitization

  • Character Validation: Only allow valid characters
  • Length Limits: Prevent excessive input sizes
  • Encoding Validation: Ensure proper encoding handling

Data Privacy

  • Local Processing: All conversion happens client-side
  • No Data Transmission: No data sent to servers
  • Memory Cleanup: Proper cleanup of sensitive data

Last updated: January 20, 2025

Was this page helpful?