如何将文本二进制code转换在JavaScript中? [英] How to convert text to binary code in JavaScript?

查看:177
本文介绍了如何将文本二进制code转换在JavaScript中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想的JavaScript在一个textarea成二进制code翻译文本。

例如,如果用户在测试到textarea的,值 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语句每个字符分配一个二进制code值(如案T:回归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?

推荐答案

你应该做的是使用字符$ C $猫函数获得ASCII码$转换每个字符C $℃的小数。然后,你可以用它转换成二进制值的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

<input id="ti1" value ="TEST"/>
<input id="ti2"/>
<button onclick="convert();">Convert!</button>

JS:

function convert() {
  var  output=document.getElementById("ti2");  
  var input=document.getElementById("ti1").value;
    output.value = "";
    for (i=0; i < input.length; i++) {
        output.value +=input[i].charCodeAt(0).toString(2) + " ";
    }
}

这是一个小提琴: http://jsfiddle.net/fA24Y/1/

这篇关于如何将文本二进制code转换在JavaScript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆