我希望JavaScript将textarea中的文本翻译成二进制代码。
例如,如果用户在“TEST
”中键入textarea,则应返回值“01010100 01000101 01010011 01010100
”。
我想避免使用switch语句为每个字符分配二进制代码值(例如case "T": return "01010100
)或任何其他类似技术。
这是一个显示我的意思的JSFiddle。这在原生JavaScript中是否可行?
答案 0 :(得分:43)
你应该做的是使用charCodeAt
函数转换每个字符以获得十进制的Ascii代码。然后,您可以使用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 (var i = 0; i < input.length; i++) {
output.value += input[i].charCodeAt(0).toString(2) + " ";
}
}
这是一个小提琴:http://jsfiddle.net/fA24Y/1/
答案 1 :(得分:21)
这可能是最简单的:
function text2Binary(string) {
return string.split('').map(function (char) {
return char.charCodeAt(0).toString(2);
}).join(' ');
}
答案 2 :(得分:8)
代码:
function textToBin(text) {
var length = text.length,
output = [];
for (var i = 0;i < length; i++) {
var bin = text[i].charCodeAt().toString(2);
output.push(Array(8-bin.length+1).join("0") + bin);
}
return output.join(" ");
}
textToBin("!a") => "00100001 01100001"
另一种方式
function textToBin(text) {
return (
Array
.from(text)
.reduce((acc, char) => acc.concat(char.charCodeAt().toString(2)), [])
.map(bin => '0'.repeat(8 - bin.length) + bin )
.join(' ')
);
}
答案 3 :(得分:7)
var PADDING = "00000000"
var string = "TEST"
var resultArray = []
for (var i = 0; i < string.length; i++) {
var compact = string.charCodeAt(i).toString(2)
var padded = compact.substring(0, PADDING.length - compact.length) + compact
resultArray.push(padded)
}
console.log(resultArray.join(" "))
答案 4 :(得分:6)
这是一个非常通用的本机实现,I wrote some time ago,
// ABC - a generic, native JS (A)scii(B)inary(C)onverter.
// (c) 2013 Stephan Schmitz <eyecatchup@gmail.com>
// License: MIT, http://eyecatchup.mit-license.org
// URL: https://gist.github.com/eyecatchup/6742657
var ABC = {
toAscii: function(bin) {
return bin.replace(/\s*[01]{8}\s*/g, function(bin) {
return String.fromCharCode(parseInt(bin, 2))
})
},
toBinary: function(str, spaceSeparatedOctets) {
return str.replace(/[\s\S]/g, function(str) {
str = ABC.zeroPad(str.charCodeAt().toString(2));
return !1 == spaceSeparatedOctets ? str : str + " "
})
},
zeroPad: function(num) {
return "00000000".slice(String(num).length) + num
}
};
并按如下方式使用:
var binary1 = "01100110011001010110010101101100011010010110111001100111001000000110110001110101011000110110101101111001",
binary2 = "01100110 01100101 01100101 01101100 01101001 01101110 01100111 00100000 01101100 01110101 01100011 01101011 01111001",
binary1Ascii = ABC.toAscii(binary1),
binary2Ascii = ABC.toAscii(binary2);
console.log("Binary 1: " + binary1);
console.log("Binary 1 to ASCII: " + binary1Ascii);
console.log("Binary 2: " + binary2);
console.log("Binary 2 to ASCII: " + binary2Ascii);
console.log("Ascii to Binary: " + ABC.toBinary(binary1Ascii)); // default: space-separated octets
console.log("Ascii to Binary /wo spaces: " + ABC.toBinary(binary1Ascii, 0)); // 2nd parameter false to not space-separate octets
来源是Github(要点):https://gist.github.com/eyecatchup/6742657
希望它有所帮助。随意使用任何你想要的东西(好吧,至少在麻省理工学院允许的任何地方)。
答案 5 :(得分:4)
只是暗示正确的方向
var foo = "TEST",
res = [ ];
foo.split('').forEach(function( letter ) {
var bin = letter.charCodeAt( 0 ).toString( 2 ),
padding = 8 - bin.length;
res.push( new Array( padding+1 ).join( '0' ) + bin );
});
console.log( res );
答案 6 :(得分:4)
带前导0的8位字符
public class Main {
public static void main(String[] args) throws IOException {
Bank bank = new Bank(20);
System.out.println("You have $" + bank.getBalance());
}
}
public class Bank{
int balance;
public Bank(int balance){
this.balance = balance;
}
public int getBalance(){
return this.balance;
}
}
如果您需要6位或7位,只需更改'sometext'
.split('')
.map((char) => '00'.concat(char.charCodeAt(0).toString(2)).slice(-8))
.join(' ');
答案 7 :(得分:2)
其他答案适用于大多数情况。但值得注意的是charCodeAt()
和相关的不能使用UTF-8字符串(也就是说,如果标准ASCII范围之外有任何字符,它们会抛出错误)。这是一种解决方法。
// UTF-8 to binary
var utf8ToBin = function( s ){
s = unescape( encodeURIComponent( s ) );
var chr, i = 0, l = s.length, out = '';
for( ; i < l; i ++ ){
chr = s.charCodeAt( i ).toString( 2 );
while( chr.length % 8 != 0 ){ chr = '0' + chr; }
out += chr;
}
return out;
};
// Binary to UTF-8
var binToUtf8 = function( s ){
var i = 0, l = s.length, chr, out = '';
for( ; i < l; i += 8 ){
chr = parseInt( s.substr( i, 8 ), 2 ).toString( 16 );
out += '%' + ( ( chr.length % 2 == 0 ) ? chr : '0' + chr );
}
return decodeURIComponent( out );
};
不推荐使用escape/unescape()
个函数。如果您需要填充,您可以查看更全面的UTF-8编码示例:http://jsfiddle.net/47zwb41o
答案 8 :(得分:1)
这似乎是简化版
Array.from('abc').map((each)=>each.charCodeAt(0).toString(2)).join(" ")
答案 9 :(得分:1)
如果您正在使用BigInt
支持的节点或浏览器中工作,此版本通过节省最后的昂贵字符串构造来降低成本:
const zero = 0n
const shift = 8n
function asciiToBinary (str) {
const len = str.length
let n = zero
for (let i = 0; i < len; i++) {
n = (n << shift) + BigInt(str.charCodeAt(i))
}
return n.toString(2).padStart(len * 8, 0)
}
这大约是此处提到的其他解决方案(包括此简单的es6 +实现)的两倍:
const toBinary = s => [...s]
.map(x => x
.codePointAt()
.toString(2)
.padStart(8,0)
)
.join('')
如果您需要处理unicode字符,请找这个人:
const zero = 0n
const shift = 8n
const bigShift = 16n
const byte = 255n
function unicodeToBinary (str) {
const len = str.length
let n = zero
for (let i = 0; i < len; i++) {
const bits = BigInt(str.codePointAt(i))
n = (n << (bits > byte ? bigShift : shift)) + bits
}
const bin = n.toString(2)
return bin.padStart(8 * Math.ceil(bin.length / 8), 0)
}
答案 10 :(得分:1)
这是尽可能短的。它基于评分最高的答案,但已转换为缩减函数。
"TEST".split("").reduce(function (a, b) { return a + b.charCodeAt(0).toString(2)}, "")
答案 11 :(得分:0)
谢谢马吉德·莱西,感谢您的answer
我从您的代码中提取了2个函数:
目标是实现将字符串转换为VARBINARY,BINARY和返回
const stringToBinary = function(string, maxBytes) {
//for BINARY maxBytes = 255
//for VARBINARY maxBytes = 65535
let binaryOutput = '';
if (string.length > maxBytes) {
string = string.substring(0, maxBytes);
}
for (var i = 0; i < string.length; i++) {
binaryOutput += string[i].charCodeAt(0).toString(2) + ' ';
}
return binaryOutput;
};
和向后转换:
const binaryToString = function(binary) {
const arrayOfBytes = binary.split(' ');
let stringOutput = '';
for (let i = 0; i < arrayOfBytes.length; i++) {
stringOutput += String.fromCharCode(parseInt(arrayOfBytes[i], 2));
}
return stringOutput;
};
答案 12 :(得分:0)
var UTF8ToBin=function(f){for(var a,c=0,d=(f=unescape(encodeURIComponent(f))).length,b="";c<d;c++){for(a=f.charCodeAt(c).toString(2);a.length%8!=0;){a="0"+a}b+=a}return b},binToUTF8=function(f){for(var a,c=0,d=f.length,b="";c<d;c+=8){b+="%"+((a=parseInt(f.substr(c,8),2).toString(16)).length%2==0?a:"0"+a)}return decodeURIComponent(b)};
这是一个很小的JavaScript代码,用于将UTF8转换为Binary,反之亦然。
答案 13 :(得分:0)
class BinStringConverter {
fromString = string => string.
split('').
map(el => el.charCodeAt(0).toString(2)).
join(' ')
fromBinary = bin => bin.
split(' ').
map(bin => String.fromCharCode(parseInt(bin, 2))).
join('')
}
const [textInput, binInput] = document.querySelectorAll('input')
const [binResult, stringResult] = document.querySelectorAll('span')
const converter = new BinStringConverter()
textInput.addEventListener('input', e => {
const { value } = e.target
binResult.innerText = converter.fromString(value)
if (value) binResult.className = 'result'
else binResult.className = 'hidden'
})
binInput.addEventListener('input', e => {
const { value } = e.target
stringResult.innerText = converter.fromBinary(value)
if (value) stringResult.className = 'result'
else stringResult.className = 'hidden'
})
* {
font-family: "Gill Sans", sans-serif;
color: #555;
padding: 0;
margin: 0;
box-sizing: border-box;
background-color: #fafafa;
}
main {
height: 100vh;
width: 100vw;
}
div {
display: flex;
flex-direction: column;
padding: 10px;
}
label {
margin-bottom: 3px;
}
input {
width: 100%;
border: none;
border-bottom: 1px solid #c1c1c1;
padding: 5px 2px;
font-size: 1.25em;
}
input:focus, input:active {
outline: none;
}
.hidden {
display: none;
}
.result {
border: 1px dashed #12664F;
padding: 5px;
border-radius: 3px;
margin-top: 5px;
background-color: #22BF95;
color: white;
position: relative;
}
<main>
<div>
<label for="string-input">From string</label>
<input name="string-input" type="text" />
<span class="hidden">
</span>
</div>
<div>
<label for="bin-input">From binary</label>
<input name="bin-input" type="text" />
<span></span>
</div>
</main>
答案 14 :(得分:-1)
尝试一下:
String.prototype.toBinaryString = function(spaces = 0) {
return this.split("").map(function(character) {
return character.charCodeAt(0).toString(2);
}).join(" ".repeat(spaces));
}
并像这样使用它:
"test string".toBinaryString(1); // with spaces
"test string".toBinaryString(); // without spaces
"test string".toBinaryString(2); // with 2 spaces