今日已更新 217 条资讯 | 累计 37466 条内容
关于我们

How to Convert Text to Binary (and Back) in JavaScript

Simran Kaur 2026年08月30日 14:53 0 次阅读 来源:Dev.to

You type "Hi" and the computer stores 01001000 01101001 . Text is just numbers wearing a costume. Here is exactly how a string turns into binary, why UTF-8 matters, and how to do the conversion both ways in a few lines of JavaScript. What "binary" actually means here Computers do not store letters. They store numbers, and every number is a run of ones and zeros. Each character maps to a code point, that number becomes a byte, and each byte is written as eight bits . The letter A has the ASCII code 65. In binary that is: 65 = 01000001 Lowercase a is 97, which is 01100001 . So the whole word "Hi" ( H = 72, i = 105) becomes: 01001000 01101001 Group the bits into bytes of 8 and you can read any binary string back into text. Text to binary in JavaScript The reliable way is TextEncoder . It hands you the raw UTF-8 bytes, so you do not have to worry about character codes above 127. function textToBinary ( text ) { const bytes = new TextEncoder (). encode ( text ); return Array . from ( bytes ) . map ( b => b . toString ( 2 ). padStart ( 8 , " 0 " )) . join ( " " ); } textToBinary ( " Hi " ); // "01001000 01101001" toString(2) gives the binary digits, and padStart(8, "0") keeps every byte a full 8 bits. Without the pad, H would come out as 1001000 (7 bits) and the string would be impossible to split back cleanly. Binary back to text Reverse the process: strip spaces, cut the string into 8-bit chunks, parse each chunk as a base-2 number, then decode the bytes with TextDecoder . function binaryToText ( bin ) { const bits = bin . replace ( / \s +/g , "" ); const bytes = new Uint8Array ( bits . length / 8 ); for ( let i = 0 ; i < bytes . length ; i ++ ) { bytes [ i ] = parseInt ( bits . slice ( i * 8 , i * 8 + 8 ), 2 ); } return new TextDecoder ( " utf-8 " ). decode ( bytes ); } binaryToText ( " 01001000 01101001 " ); // "Hi" Two checks worth adding in real code: reject anything that is not 0 or 1 , and reject a bit count that is not a multiple of 8. Those two guards catch almo

本文内容来源于互联网,版权归原作者所有
查看原文