How to convert text to binary code in JavaScript?(如何在 JavaScript 中将文本转换为二进制代码?)
问题描述
我希望 JavaScript 将 textarea 中的文本翻译成二进制代码.
例如,如果用户输入TEST
"进入文本区域,值01010100 01000101 01010011 01010100
"应该退货.
For example, if a user types in "TEST
" into the textarea, the value "01010100 01000101 01010011 01010100
" should be returned.
我想避免使用 switch 语句为每个字符分配一个二进制代码值(例如 case "T": return "01010100
)或任何其他类似技术.
I would like to avoid using a switch statement to assign each character a binary code value (e.g. case "T": return "01010100
) or any other similar technique.
这里有一个 JSFiddle 来说明我的意思.这在原生 JavaScript 中可行吗?
Here's a JSFiddle to show what I mean. Is this possible in native JavaScript?
推荐答案
你应该做的是使用 charCodeAt
函数将每个字符转换为十进制的ASCII码.然后您可以使用 toString(2)
将其转换为二进制值:
What you should do is convert every char using charCodeAt
function to get the Ascii Code in decimal. Then you can convert it to Binary value using toString(2)
:
HTML:
JS:
这是一个小提琴:http://jsfiddle.net/fA24Y/1/
这篇关于如何在 JavaScript 中将文本转换为二进制代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!