import React, { useState, useEffect } from 'react'; const BinaryConverter = ({ addToMessage, sharedInput, setSharedInput }) => { const [output, setOutput] = useState(''); const [copied, setCopied] = useState(false); const [toBinary, setToBinary] = useState(true); const [hasError, setHasError] = useState(false); const convertToBinary = (text) => { let binary = ''; for (let i = 0; i < text.length; i++) { binary += text[i].charCodeAt(0).toString(2) + ' '; } setOutput(binary.trim()); setHasError(false); }; const convertFromBinary = (binary) => { try { let text = ''; const binaryChars = binary.split(' '); for (let binaryChar of binaryChars) { if (binaryChar) { const decimal = parseInt(binaryChar, 2); if (isNaN(decimal)) { throw new Error('Invalid binary string'); } text += String.fromCharCode(decimal); } } setOutput(text); } catch (error) { setOutput('Error: Invalid binary string'); } }; const handleInputChange = (e) => { const newText = e.target.value; // Limit input to 50,000 characters to prevent performance issues if (newText.length > 50000) { return; } setSharedInput(newText); if (toBinary) { convertToBinary(newText); } else { convertFromBinary(newText); } }; // Recalculate output when component mounts or sharedInput changes from another converter useEffect(() => { if (sharedInput) { if (toBinary) { convertToBinary(sharedInput); } else { convertFromBinary(sharedInput); } } else { setOutput(''); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [sharedInput, toBinary]); const copyToClipboard = () => { navigator.clipboard.writeText(output); setCopied(true); setTimeout(() => setCopied(false), 2000); }; const swapConversion = () => { const oldInput = sharedInput; setSharedInput(output); setOutput(oldInput); setToBinary(!toBinary); }; return (

💻 Binary Converter