w

API参考

本文档提供文本转ASCII二进制转换器实现的技术细节,包括转换算法、数据结构和集成选项。

转换算法

文本转二进制转换

算法概述

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

分步过程

  1. 文本编码:使用指定编码将文本转换为字节数组
  2. 字节处理:逐个处理每个字节
  3. 二进制转换:将每个字节转换为8位二进制字符串
  4. 填充:确保每个二进制字符串恰好为8位
  5. 格式化:应用选定的格式(空格、连续、分组)

编码支持

  • UTF-8:多字节Unicode编码
  • ASCII:7位字符编码(0-127)
  • Latin-1:8位扩展ASCII(0-255)

二进制转文本转换

算法概述

function binaryToText(binaryString, encoding = 'utf8') {
  // 删除空格并验证
  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));
}

分步过程

  1. 输入验证:检查有效的二进制字符(0和1)
  2. 长度验证:确保长度是8的倍数
  3. 分组:将二进制字符串分成8位组
  4. 十进制转换:将每个8位组转换为十进制
  5. 字符重构:将十进制值转换为字符
  6. 文本组装:将字符组合成最终文本

数据结构

输入验证

二进制输入验证

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

  // 检查有效字符
  if (!/^[01]+$/.test(cleanBinary)) {
    throw new Error('Invalid binary input. Please enter only 0s and 1s.');
  }

  // 检查长度
  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;
}

字符代码验证

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

格式化函数

二进制格式化

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

输出统计

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

历史管理

历史数据结构

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

历史操作

// 添加到历史
function addToHistory(record) {
  const history = getHistory();
  history.unshift(record);

  // 限制为50条记录
  if (history.length > 50) {
    history.splice(50);
  }

  saveHistory(history);
}

// 从历史加载
function loadFromHistory(record) {
  return {
    textInput: record.textInput,
    binaryInput: record.binaryInput,
    encoding: record.encoding,
    binaryFormat: record.binaryFormat,
  };
}

错误处理

错误类型

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.',
};

错误处理策略

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}`);
}

性能考虑

内存管理

  • 输入限制:合理的限制以防止内存问题
  • 垃圾回收:适当清理临时对象
  • 高效算法:优化的转换函数

浏览器兼容性

  • TextEncoder/TextDecoder:现代浏览器支持
  • 回退选项:旧浏览器的替代实现
  • 功能检测:检查API可用性

集成选项

独立使用

// 导入转换函数
import { textToBinary, binaryToText } from './converter';

// 在您的应用程序中使用
const binary = textToBinary('Hello', 'utf8', 'spaced');
const text = binaryToText('01001000 01100101 01101100 01101100 01101111');

组件集成

<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>

测试

单元测试

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

集成测试

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

安全考虑

输入清理

  • 字符验证:只允许有效字符
  • 长度限制:防止过大的输入
  • 编码验证:确保适当的编码处理

数据隐私

  • 本地处理:所有转换都在客户端进行
  • 无数据传输:不向服务器发送数据
  • 内存清理:适当清理敏感数据

最后更新:2025年1月20日

这个页面对您有帮助吗?