Shr*_*pta 41 javascript string binary
我希望JavaScript将textarea中的文本翻译成二进制代码.
例如,如果用户在TEST
textarea中键入" ",01010100 01000101 01010011 01010100
则应返回值" ".
我想避免使用switch语句为每个字符分配二进制代码值(例如case "T": return "01010100
)或任何其他类似技术.
这是一个JSFiddle来展示我的意思.这在原生JavaScript中是否可行?
Maj*_*ssi 45
你应该做的是使用charCodeAt
函数转换每个char 以获得十进制的Ascii代码.然后你可以使用toString(2)
以下方法将其转换为二进制值:
HTML:
<input id="ti1" value ="TEST"/>
<input id="ti2"/>
<button onClick="convert();">Convert!</button>
Run Code Online (Sandbox Code Playgroud)
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) + " ";
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个小提琴:http://jsfiddle.net/fA24Y/1/
gnc*_*ais 23
这可能是最简单的:
function text2Binary(string) {
return string.split('').map(function (char) {
return char.charCodeAt(0).toString(2);
}).join(' ');
}
Run Code Online (Sandbox Code Playgroud)
码:
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"
Run Code Online (Sandbox Code Playgroud)
其他方式
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(' ')
);
}
Run Code Online (Sandbox Code Playgroud)
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(" "))
Run Code Online (Sandbox Code Playgroud)
这是我前段时间写的一个非常通用的本机实现,
// 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
}
};
Run Code Online (Sandbox Code Playgroud)
并按如下方式使用:
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
Run Code Online (Sandbox Code Playgroud)
来源是Github(要点):https://gist.github.com/eyecatchup/6742657
希望能帮助到你.随意使用任何你想要的东西(好吧,至少麻省理工学院允许的话).
其他答案适用于大多数情况。但值得注意的是,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 );
};
Run Code Online (Sandbox Code Playgroud)
escape/unescape()
不推荐使用这些功能。如果您需要它们的 polyfill,您可以查看更全面的 UTF-8 编码示例:http : //jsfiddle.net/47zwb41o
只是提示正确的方向
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 );
Run Code Online (Sandbox Code Playgroud)
前导 0 的 8 位字符
'sometext'
.split('')
.map((char) => '00'.concat(char.charCodeAt(0).toString(2)).slice(-8))
.join(' ');
Run Code Online (Sandbox Code Playgroud)
如果你需要6位或7位,只需更改.slice(-8)
感谢Majid Laissi的回答
我从您的代码中创建了 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;
};
Run Code Online (Sandbox Code Playgroud)
和向后转换:
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;
};
Run Code Online (Sandbox Code Playgroud)
这是一个工作示例:https : //jsbin.com/futalidenu/edit?js,console